我想让用户向现有的arraylist添加一个元素,并且使用一些与arraylist元素相关的变量,arraylist是:
所以我写了下面的代码:
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++;
这是从菜单中选择的东西&#34;添加一个新的水果店&#34;,所以每次用户添加水果店时,该对象将被称为newShop,然后旧的newShop将被删除!怎么能避免这个错误?
p.s:FruitShop由其他类组成:Apples和OwnerInfo
提前谢谢。
答案 0 :(得分:2)
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.
最后转移你的陈述
shops.add(newShop);
。初始化完成后。
答案 1 :(得分:0)
完成所有shops.add(newShop);
更改后,您必须插入行newShop
。当然,将ArrayList<FruitShop> shops
作为实例变量。每次调用方法后都不要创建新列表。
public class A {
private List<FruitShop> shops= new ArrayList<FruitShop>();
public void addShop() {
...
shops.add(newShop);
}
}