【发布时间】:2019-05-19 03:14:48
【问题描述】:
我正在尝试使用 do-while 循环将用户输入添加到 Arraylist,但是我一直以一个列表结束,该列表仅包含重复多次输入的最终项目。
public static ArrayList<Item> purchaseItems()
{
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
do {
response = in.nextLine();
if(!response.equals("done") ){
toBuy.add(new Item(response, randGen.nextInt(100)));
System.out.println(toBuy);
}
} while(!response.equals("done"));
return toBuy;
}
【问题讨论】:
-
在您的问题中包含 Item 类
-
如果要打印列表中的所有项目,则需要遍历列表
-
它对我有用。请分享您的整个代码,或告诉我们/我您如何假设列表仅包含重复项
-
你的字段在
Item或者static吗? -
哦,是的,这些字段是静态的,因此修复了它。谢谢!!!!