find a specific object in a ArrayList - java

I am making a small program that should have a class for people(Name, BirthYear) and a class for pets(Name, AnimalType).
In the main I have created a menu so a user can add peoples then the pets.
Now to my question, if I create 4 people "Bruce, Tony, Kevin, William" and the user want to give Kevin a pet, how can i know where in the list Kevin are? Becuse you cant use the contains(), can you? well i cant anyways...
The thing is that I have a method in the class for people that creates the pet, because I want them to be linked...
public void setAnimal(String dName, String dType)
{
Animal.add(new Pet(dName, dType));
}
This is how my method to create pets work..
private static void createA()
{
String P = JOptionPane.showInputDialog(null,"This is the people you can give a pet, please write a name:\n" + People);
P = P.toUpperCase();
//I want to write some code here to give a int a number so i cant but it in the get downbelow insted //of "???"
boolean b =true;
while (b != false)
{
try
{
ggr3 = Integer.parseInt(JOptionPane.showInputDialog("How many pets do you want to add: "));
b = false;
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e + "\nWrite with numbers!");
}
}
while (ggr3 != ggr4)
{
dNamn = JOptionPane.showInputDialog("Write the name: ");
dTyp = JOptionPane.showInputDialog("Write animal type: ");
People.get(???).setAnimal(dName, dType);
ggr4++;
}
}

Becuse you cant use the contains(), can you?
yes you can only you need to do is to override equals() method based on your requirement

List<Person> arr = new ArrayList<Person>();
Person kevin = new Person("kevin");
arr.add(kevin);
Person newKevin = arr.get(kevin);
System.out.println(kevin == newKevin); // True b/c they point to the same object.
System.out.println(kevin.equals(newKevin)); // True b/c they have equal values.
You need to add a .equals() method to your Person class.

The way of searching for an object in an array list is with the indexOf method.
Example:
int x = myAList.indexOf(myObject)
It returns the position of myObject in the ArrayList or -1 if it's not there.

Related

How can I show segmented information in an array?

I have to create a program which has a list of houses. In this houses there has to be this information:
direction, zipcode, number of rooms and the square meters of the house.
One of my biggest problems is that this information has to be segmented. So, first the list of directions have to be shown, then the list of zipcodes, then the number of rooms...
I created a class House and I set the String variables for each one (direction, zipcode, number of rooms and the square meters of the house).
I know that I should be using arrays, for and objects but It's my first assignment and I am really lost on how or where should I start.
I really want to learn how to do it, so if you have any idea, tip or suggestion I would appreciate it. I don't want people to do my assignment I just want to know how can I get started.
thank you!
This is my code so far:
package ejerciciofinalt3;
public class HouseExercise {
public static void main(String[] args) {
// TODO Auto-generated method stub
House house1 = new House();
house1.showHouseInfo();
house1.direction = "abc";
house1.postCode = "08397";
house1.roomNumber = "4";
house1.squareMeter = "100";
house1.showHouseInfo();
}
}
Create an ArrayList and add each house in that List. Then for each of the segments (directions, zipCodes, etc) do a for loop and print the segment:
List <House> houseL = new ArrayList();
houseL.add(house1);
houseL.add(house2);
houseL.add(house3);
System.out.println("-- Directions --");
for (House house:houseL){
System.out.println(house.getDirection());
}
System.out.println("-- Zip Codes--");
for (House house:houseL){
System.out.println(house.getPostCode());
}
//etc
You should have getters in House class.
Initialize a String Array like this:
String[] housePropertiesArray = new String[]{"abc", "08397", "4", "100"};
...in the House class.
Then you could write a method to return all of them:
public String getProperties(){
String output = "";
for(String property : housePropertiesArray){
output += property + "\n";
}
return output;
}
In the outputString you would have a superfluous \n in the end, just a newLine-Tag but wouldnt matter much I hope.
Try to override the toString() method like
class House{
...
#override
public String toString(){
return String.format("direction: %s postCode: %s roomNumber: %s squareMeter : %s",
this.direction, this.postCode, this.roomNumber, this.squareMeter);
}
after if you want to display just call
System.out.println(house.toString());
Or
System.out.println(house);

How to pull specific data from an object in an arraylist

Ok, not sure if the title worded that correctly but say I have three objects with two strings of data each(Lets say a stateName and a cityName) stored into an arraylist. Is it possible to enter in a state name in as a string variable(call it searchStateName), then have a method search through the objects in the list and compare searchStateName to the stateName inside each object in the arraylist, and when a match is found have it return the cityName that is inside the same object as the matching stateName?
I am trying to do something similar currently and would like to figure it out myself, but I have been working on this for the past hour and am completely lost. Could anyone point me in the right direction?
This is the approach. Say you have a class called SC and you have two instance variables in it and getters and setters for them. You need to initialize 3 objects of them inside your main:
SC a = new SC("Illinois ","Chicago ");
SC b = new SC("Michigan ","Detroit");
SC c = new SC("New York"," New York");
And then create an ArrayList of object SC and add those 3 objects of SC to that ArrayList.
ArrayList<SC> list = new ArrayList<SC>();
list.add(a);
list.add(b);
list.add(c);
Now call the method that search for a state name and returns the city name if it finds it:
this.searchStateName("Illinois");
The actual implementation of this method with for-each loop:
public String searchStateName(String stateName){
String result = "No city found.";
for (SC sc : list )
if (sc.getStateName().equalsIgnoreCase(stateName)){
result = sc.getCityName();
break;
}
}
return result;
}
If you are not comfortable with for-each loop then you can use the regular for loop below. I commented out on purpose. But it will work correctly and give you the correct city name.
//public String searchStateName(String stateName){
// String result = null;
// for (int i = 0; i < list.size(); i++){
// if (list.get(i).getStateName() .equalsIgnoreCase(stateName)){
// result = list.get(i).getCityName();
// break;
// }
// }
// return result;
//}
And thats it. Let me know if you need help further.

For Each Loops and For Loops Java

I want to be able to create a for loop like this
For(each booking)
sounds simple for all you experts out there, but ive tried researching how to do this,
and its left me a little confused,
I assume id need a for each loop, which would be something like this
for (type var : coll) {
body-of-loop
}
This program creates a new booking and then allows the user to enter the details into the program of that booking, I have named this B1. IS it that value you enter into the for loop?
I know ill get rated down on this, but i dont understand how i get it to loop for each booking.
Thanks for the quick answers, Ive written some code which ill provide now. Hopefully it will make it easier to see.
Booking Class
public class Booking
{
private int bookingId;
private String route;
private double startTime;
private String bookingDate;
public Booking()
{
bookingId = 0000;
route = "No Route Entered";
startTime = 0.00;
bookingDate = "No Date entered";
}
public int getBookingId()
{
return bookingId;
}
public String getRoute()
{
return route;
}
public double getStartTime()
{
return startTime;
}
public String getBookingDate()
{
return bookingDate;
}
public void setBookingId(int bookingId)
{
this.bookingId = bookingId;
}
public void setRoute(String route)
{
this.route = route;
}
public void setStartTime(double startTime)
{
this.startTime = startTime;
}
public void setBookingDate(String bookingDate)
{
this.bookingDate = bookingDate;
}
public Booking(int bookingId, String route, double startTime, String bookingDate)
{
setBookingId(bookingId);
setRoute(route);
setStartTime(startTime);
setBookingDate(bookingDate);
}
public String toString()
{
return "BookingId: " + getBookingId() + "\nRoute: " + getRoute() + "\nStart Time: " + getStartTime() +
"\nBooking Date: " + getBookingDate();
}
}
Main Class
import java.util.*;
public class Main {
public static void main(String[] args) {
//<editor-fold defaultstate="collapsed" desc="Creates new Student and booking">
Student s1 = new Student();
Booking b1 = new Booking();
s1.setStudentId(Integer.parseInt(JOptionPane.showInputDialog("Enter ID for Student: [0001]")));
s1.setFname(JOptionPane.showInputDialog("Enter first name of Student: "));
s1.setLname(JOptionPane.showInputDialog("Enter last name of Student: "));
s1.setAddress(JOptionPane.showInputDialog("Enter address for Student: "));
s1.setPhoneNo(JOptionPane.showInputDialog("Enter phone number for Student: "));
s1.setOtherDetails(JOptionPane.showInputDialog("Enter other details for Student: [Glasses?]"));
b1.setBookingId(0002);
b1.setStartTime(Double.parseDouble(JOptionPane.showInputDialog("Enter Start time for Booking: [1200]")));
b1.setBookingDate(JOptionPane.showInputDialog("Enter Date for Booking: [01-JAN-12]"));
//</editor-fold>
//For Each Booking
}
}
}
List <Booking> allBookings = new ArrayList<Booking>();
//fill your AllBookings with data
for(Booking b:allBookings){
body of loop // b is your actual Booking Object
}
Something like this would do your work.
You will need an Booking Class, and some data stored in your AllBookings Array List. With you ensure that only Booking Objects can be placed within that Array List.
But back to the For each loop.
The first part (Booking) defines which Object-type is placed in
the list,array or what you want to compute through. Note: You could also place Object instead of Booking since everything is an Object, but I would not recommend you to do that.
The second one (b) is the name of the variable which stands for
the actual element in your list, when iterating over it.
And the third and final part (AllBookings) is your Collection or Array where all your Objects are placed in.
Java Documentation for For-Each Loops:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
You got the syntax right, you just need to pass a collection (or an array) of the objects to the loop:
// bookings is Booking[] or a collection of Booking objects, like List<Booking>
for (Booking b : bookings)
{
// do whatever you need to do with b
}
Type is the name of the type of your object: the thing you'd use to declare it. E.G. Booking.
var is the name of the placeholder variable, which will assume the value of each element that you loop over in the collection. This can be whatever you want.
coll is the name of the collection you want to loop over. It sounds like maybe you called this B1.
So you would use
for (Booking booking : B1){
//body
}
What is booking? foreach loops are used for Array Iteration
I'm assuming this is what you're trying to do, lets say booking is an array of type String[] (i can edit my answer if it's something else)
String[] booking = new String[]{"Hello", "How are You", "Goodbye"};
for (String s: booking)
{
System.out.println(s);
}
for (int i=0; i < booking.length; i++)
{
System.out.println(booking[i]);
}
Produces the following output:
Hello
How are You
Goodbye
Hello
How are You
Goodbye
If you have a collection of type Foo like this:
List<Foo> someList = getSomeList();
Then to loop you can do:
for(Foo myFoo : someList){
System.out.println("I have a foo : "+myFoo);
}
I don't fully understand what you're asking in the paragraph where you mention B1, as what you're describing doesn't seem to require looping at all.
But in general, the for-each loop works the way you've described. Note that the right hand variable is called coll - this is because it needs to be some sort of collection of elements (strictly something that implements Iterable). So if you have e.g. a List<Booking>, you could loop over all of the bookings in this list in turn as follows:
List<Booking> bookings = ...; // populated somehow, or passed in, whatever
for (Booking b : bookings) {
// Do what you want to b, it will be done in turn to each booking in the list
// For example, let's set the hypothetical last updated date to now
b.setLastUpdated(new Date());
}
// At this point all bookings in the list have had their lastUpdated set to now
Going back to what you described:
This program creates a new booking and then allows the user to enter the details into the program of that booking, I have named this B1.
It sounds like you have a booking. Are you sure you need a loop for just one booking? A loop involves performing the same actions on a bunch of different objects; what is it you want to loop over?

Recursive java method, get mother, grand mother, great grand mother and so on

I have a list Dogs in a text file with the following format:
id:fatherid:motherid:born:owner:breed
ex:
3:2:1:2000:Scotty:Peter:dachs
I then populate an array list with objects of dog. I Need a method that returns all the mothers for a dog with a given id. I already have methods for: getMother, getDog, getChildren, getParents, existDog. getDog and getMother returns a Dog, getChildren and getParents returns a String. Now i need a method that gives me the mother, grand mother, great grand mother and so on. I do not know how to make this method. This code gives me the mother and grand mother of a dog:
public String getMotherTree(int id) {
String output = "";
if (existDog(id)) {
Dog mother = GetMother(id);
output += mother.toString();
int morId = mother.getId();
Dog grandMother= GetMother(motherId);
output += grandMother.toString;
return output;
}
output = "The dog with that id do not exist!";
return output;
}
I think that what i need is a recursive method, but i do not know how to do this.
Basically, you'd create a method that calls itself with another parameter unless some condition is met.
In your case, you might use getMotherTree() (or some adjusted method):
public String getMotherTree(int id) {
String output = "";
if (existDog(id)) {
Dog mother = GetMother(id);
output += mother.toString();
int morId = mother.getId();
return output + ", " + getMotherTree(morId); //recursion
}
//return an empty string if the dog doesn't exist
//this basically ends the recursion
return output;
}
As BalusC pointed out recursion is not necessary here, so please view that as a learning exercise only.
You don't need recursion for this: you could replace your IF with a WHILE, and after adding the mother to the String, replace id with the id of the mother. (If you still want a message if the dog doesn't exist, just check if output is blank or not before returning.)
Note that you have a logic problem (which what I just described doesn't solve): just because a dog exists doesn't mean it has a mother (or your loop/recursion would never end!), so calls to any method of this missing mother should fail.
It can be done recursively (which is computationally expensive but perhaps simpler code to understand) or can be done iteratively. Here's an iterative solution:
public String getMotherTree(int id) {
if (!existDog(id)) {
return "The dog with that id do not exist!";
}
StringBuilder output = new StringBuilder();
for (Dog mother = GetMother(id); mother != null; mother = mother.getMother()) {
if (output.length() > 0) {
output.append(", ");
}
output.append(mother.toString());
}
return output.toString();
}
This assumes that aDog.getMother() returns null if aDog has no mother in the data base.

Java - Add an object to an arraylist, then adding another to the arraylist causes the first element to be overwritten

I'm currently doing my third year programming project and its a folio tracker. :/ I have crated Stock_API and Portfolio_API interfaces (and implementations of them) and a GUI class which when instantiated takes two parameters as so:
public GUI(Portfolio_API p, Stock s){
tempPort = p;
tempStock = s;
}
I use this constructor as a way of getting implementations of these interfaces into the GUI without exposing the implementation to the GUI (which is one of the main objectives of this project). A portfolio object has a name(string) and an ArrayList. A stock object has a ticker symbol(string), a stock name(string), a share value(float), a number of shares(int) and a value of holding(float).
In the GUI i have a portCollection array list which holds objects of type portfolio_API and this is so the system can keep track of multiple portfolios. Also as mentioned in the block of code above has a tempStock and tempPort object.
Sorry to give u so much detail about the program but i thought it best so i could get the context across. Anyway, the problem at hand. I have a method which uses the GUI to get a ticker symbol, a stock name and a number of shares and adds the stock to the current portfolio open(each portfolio has its own tab). The method looks like this:
public void addStock() {
int num_shares = 0;
float dailyChange = 0.0f;
float stockValue = 0.0f;
boolean succeed = true;
// GUI gets information of stock from user
String ticker = JOptionPane.showInputDialog(frame,
"Enter the ticker symbol:");
String stockName = JOptionPane.showInputDialog(frame,
"Enter the Stock name:");
try {
num_shares = Integer.parseInt(JOptionPane.showInputDialog(frame,
"Enter the number of shares:"));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame,
"Number of shares was not an integer. Try again");
succeed = false;
}
// If parsing was successful...
if (succeed) {
tempStock.setTicker(ticker);
tempStock.setNumberOfShares(num_shares);
tempStock.setStockName(stockName);
// Fetches newest value using the current ticker symbol
boolean succeedUpdate = tempStock.updateShareValue();
if (succeedUpdate) {
tempStock.calculateValueOfHolding();
// Adds to the current portfolio...
String tabName = tabbedPane.getTitleAt(tabbedPane
.getSelectedIndex());
System.out.println(tabName);
findPortfolio(tabName).addStock(tempStock);
findPortfolio(tabName).sort();
// ...Then adds it to the table
JPanel j = (JPanel) tabbedPane.getSelectedComponent()
.getComponentAt(0, 0);
JViewport v = ((JScrollPane) j.getComponent(0)).getViewport();
JTable table = (JTable) v.getComponent(0);
float currentTotal = findPortfolio(tabName).getTotal();
// Updates the total label
((JLabel) j.getComponent(1)).setText("Total: " + currentTotal);
Object[] newStock = { tempStock.getTicker(),
tempStock.getStockName(),
tempStock.getNumberOfShares(),
tempStock.getShareValue(),
tempStock.getValueOfHolding() };
((DefaultTableModel) table.getModel()).addRow(newStock);
}
}
}
When I add more than one stock, the new stock takes place of the old one an effectively overwrites it. I think its the reuse of tempStock that is doing it. Not sure why though as surely if i add the variable to an arraylist it becomes part of that arraylist and needs no association with the tempStock variable?
Methods that are used with the mentioned arraylists :
private Portfolio_API findPortfolio(String name) {
Portfolio_API p = null;
for (int i = 0; i < portCollection.size(); i++) {
if (portCollection.get(i).getName() == name) {
p = portCollection.get(i);
}
}
These two are in the Portfolio class:
#Override
public boolean addStock(Stock_API s) {
if (!doesExist(s)) {
portfolio.add(s);
return true;
} else {
return false;
}
}
#Override
public boolean doesExist(Stock_API s) {
boolean found = false;
for (int i = 0; i < portfolio.size(); i++) {
if (portfolio.get(i).getTicker() == s.getTicker()) {
found = true;
}
}
return found;
}
I've only come here for help because i have hit a brick wall and I really need help. If anyone could give me any suggestions, i'd be eternally in your debt.
Thanks,
Chris
Yes, I think you are right when you say you think it's because you're reusing the tempStock variable. This variable still references the original object so calling setTicker() etc on tempStock also changes the object referenced by your ArrayList because it's the same object. Try reinitialising your tempStock and see if it makes a difference:
// If parsing was successful...
if (succeed) {
tempStock = new Stock(); // or however you instantiate this object
tempStock.setTicker(ticker);
tempStock.setNumberOfShares(num_shares);
tempStock.setStockName(stockName);
Thanks guys for all your input. #oracle certified professor helped with the stock problems after adding an overloaded method for addStock but turned out the same problems plagued portfolio.
What I did was create a makePortfolio method in Portfolio_API to create a new portfolio and return it. That way it avoids any nasty overwrite, gonna add it to stock too just now.
Thanks again guys. Good night! :)

Categories

Resources