gpt4 book ai didi

java - 用户将元素添加到数组列表

转载 作者:行者123 更新时间:2023-11-30 08:38:48 25 4
gpt4 key购买 nike

我想让用户添加一个元素到一个已经存在的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++;

这是从菜单“添加新水果店”中选择的东西,所以每次用户添加水果店时,对象都会被称为 newShop,然后旧的 newShop 将被删除!怎样才能避免那个错误呢?p.s: FruitShop 由其他类组成:Apples 和 OwnerInfo提前谢谢你。

最佳答案

 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.

关于java - 用户将元素添加到数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36388978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com