2017-12-03 138 views
1

我编写了代码来存储用户输入的美元金额的值。只要程序提示用户,“你想输入项目 - 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,以便每当用户想要输入新值时它是全新的? My output

回答

2
cartItems.clear(); 

把它在循环结束时,结果被输出到控制台之后。 它将刷新列表并删除其中的所有元素。

1

while循环

List<Double> cartList = new ArrayList<Double>(); 

所以现在每次用户选择是,该程序在while循环进入,然后没有任何价值,创建列表的一个新实例创建列表的实例。如果要将值存储在上一个列表中,请在创建列表的新实例之前将其写入持久性存储器(如文件或数据库)。

另外,您还可以使用

cartList.clear(); 

但是,我不建议这样做so.It可以给你的垃圾价值观和需要的时间更多的量。清除方法基本上遍历列表的所有元素,并像这样做它们为null。

for(int i = 0; i < cartList.size(); i++){ 
    cartList.get(i) = null; 
} 
3

在无处可以重置ArrayList

当你完成你的处理并且你正在循环下一轮(在外部的底部)时,你可以调用cartItems.clear()

 ... 
     while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n"))) 
     { 
      System.out.print("Sorry - we need a y/n: "); 
      response = textReader.nextLine(); 
      System.out.println(); 
     } 
     cartItems.clear(); 
    }