有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

嵌套在While循环中的ArrayList中的java重置值

我编写代码来存储用户输入的美元金额的值。每当程序提示用户“是否要输入项目-是/否?”然后,用户可以输入存储在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();
    }

但是当我第二次输入值时,我注意到程序没有清除我第一次输入的值。我为提示用户输入另一组值而编写的代码与我为初始提示编写的代码相同。我将这些第二个提示嵌套在一个while循环中,该循环由用户在初始提示中选择“y”触发

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) 个答案

  1. # 1 楼答案

    cartItems.clear();
    

    将结果打印到控制台后,将其放在循环的末尾。 它将刷新列表并删除其中的所有元素

  2. # 2 楼答案

    在while循环中创建list的实例

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

    现在,每当用户选择yes,程序就会进入while循环,然后创建一个没有任何值的list的新实例。如果要存储上一个列表中的值,请在创建列表的新实例之前将其写入持久性存储,如文件或数据库

    或者,您也可以使用

    cartList.clear();
    

    但是,我不建议这样做。它可能会给你垃圾价值观,并需要更多的时间。clear方法基本上迭代list的所有元素,并像这样将它们设置为null

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