我编写了代码来存储用户输入的美元金额的值。只要程序提示用户,“你想输入项目 - y/n?”然后用户可以输入存储在ArrayList中的值。嵌套在while循环中的ArrayList中的重置值
初始提示如下。它似乎工作,因为我可以把值没有明显的错误。
System.out.print("Would you like to input item/s - y/n: ");
String response = textReader.nextLine();
System.out.println();
// create while loop to restrict responses to single characters
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
但是,当我去放值的第二次,我注意到程序不会从我的第一个条目清除出值。我编写的用于提示用户输入另一组值的代码与我为初始提示编写的代码相同。我在由用户选择“y”触发的一个while循环中嵌套第二个提示。
while ((response.equalsIgnoreCase("y")))
{
System.out.print("Please enter an item price, or -1 to exit: $");
double values = numberReader.nextDouble();
while ((values > (-1)))
{
cartItems.add(values);
System.out.print("Please enter another item price, or -1 to exit: $");
values = numberReader.nextDouble();
}
System.out.println();
System.out.println("********** Here are your items **********");
// I omitted the code here to make this more concise.
// prompt the user to input a second round of values
System.out.print("Would you like to input item/s - y/n: ");
response = textReader.nextLine();
System.out.println();
// create while loop to restrict responses to single characters
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
}
我的输出结果如下。当我再次收到提示时,我选择'y'添加更多项目。但是,我新添加的项目$ 3.00会从第一个提示中添加到列表中。无论如何刷新或擦除ArrayList,以便每当用户想要输入新值时它是全新的?