Reputation: 37
I want to let the user add an element to an existed arraylist and intilazied some variables that are related to the element of the arraylist, the arraylist is:
so I wrote the following code:
ArrayList<FruitShop> shops= new ArrayList<FruitShop>();
Scanner in= new Scanner(System.in);
FruitShop newShop = new FruitShop(null,0.0, new Apples(), new OwnerInfo());
shops.add(newShop);
System.out.println("What is the name of new shop?: ");
newShop.setShopName(int.next());;
System.out.println("Enter initial balance in USD: ");
newShop.setBalance(Double.parseDouble(in.next()));
System.out.println("Enter owner name: ");
newShop.getShopOwner().setName(in.next());
System.out.println("Enter owner age: ");
newShop.getShopOwner().setAge(Integer.parseInt(in.next()));
System.out.println("How many apples does the store have?: ");
newShop.getApplesInfo().setQuantity(Integer.parseInt(in.next()));
System.out.println("What is the price of each apple?:");
newShop.getApplesInfo().setPrice(Double.parseDouble(in.next()));
System.out.println("Your shop has been added! ");
FruitShop.ID= ID;
ID++;
the thing this is a choice from a menu " add a new fruit shop", so every time the user will add a fruit shop the object will be called newShop and then the older newShop will be deleted! how can avoid that mistake? p.s: FruitShop is composed from to other classes: Apples and OwnerInfo Thank you in advance.
Upvotes: 2
Views: 80
Reputation: 49606
You have to insert the line shops.add(newShop);
after all newShop
changes are done. And, of course, make ArrayList<FruitShop> shops
as an instance variable. Don't create a new list after each call of your method.
public class A {
private List<FruitShop> shops= new ArrayList<FruitShop>();
public void addShop() {
...
shops.add(newShop);
}
}
Upvotes: 0
Reputation: 6846
ArrayList<FruitShop> shops= new ArrayList<FruitShop>();
Scanner in= new Scanner(System.in);
FruitShop newShop = new FruitShop(null,0.0, new Apples(), new OwnerInfo());
System.out.println("What is the name of new shop?: ");
newShop.setShopName(int.next());;
System.out.println("Enter initial balance in USD: ");
newShop.setBalance(Double.parseDouble(in.next()));
System.out.println("Enter owner name: ");
newShop.getShopOwner().setName(in.next());
System.out.println("Enter owner age: ");
newShop.getShopOwner().setAge(Integer.parseInt(in.next()));
System.out.println("How many apples does the store have?: ");
newShop.getApplesInfo().setQuantity(Integer.parseInt(in.next()));
System.out.println("What is the price of each apple?:");
newShop.getApplesInfo().setPrice(Double.parseDouble(in.next()));
System.out.println("Your shop has been added! ");
shops.add(newShop); // add last of the line when all initialization is done.
Shift your statement
shops.add(newShop);
at last. After initialization is getting done.
Upvotes: 2