【问题标题】:How do I correctly use a while-loop to fill 2 Arraylists with user input?如何正确使用 while-loop 用用户输入填充 2 个 Arraylist?
【发布时间】:2019-07-03 04:09:08
【问题描述】:

我正在尝试编写一个程序,要求用户首先输入一个名称(字符串),然后输入一个数量(双精度)并将输入放入 2 个单独的数组列表中。这是通过一个while循环完成的。用户完成后,他们可以按 0,然后程序将打印两个数组列表。 第一次循环很完美,第二次它将打印要求输入的两行,而不允许在两者之间输入。当第二次给定输入时,它将显示 InputMismacchtException。

Scanner userInput = new Scanner(System.in);
ArrayList<String> customerName = new ArrayList<>();
ArrayList<Double> customerSpend = new ArrayList<>();
double checkUserInput = 1;

while (checkUserInput != 0) {
    System.out.println("Please enter the customer name");
    customerName.add(userInput.nextLine());
    System.out.println("Please enter the customer amount");
    customerSpend.add(userInput.nextDouble());
    if (customerSpend.get(customerSpend.size()-1) == 0){
        checkUserInput = 0;
    }
}
for (int i = 0; i < customerName.size(); i++) {
    System.out.println(customerName.get(i)+customerSpend.get(i));
}

【问题讨论】:

    标签: java arraylist while-loop user-input


    【解决方案1】:

    nextDouble() 仅读取行中的标记,不会读取完整行。所以当nextLine()被执行时,它会读取剩余的行,而你在控制台中输入的name将被nextDouble()读取并抛出InputMismachtException

    将输入的下一个标记扫描为双精度。

    为了避免这种情况,您可以使用nextLine() 并将值解析为Double

    您可以使用nextLine() 并将值解析为Double

    while (checkUserInput != 0) {
        System.out.println("Please enter the customer name");
        customerName.add(userInput.nextLine());
        System.out.println("Please enter the customer amount");
        customerSpend.add(Double.parseDouble(userInput.nextLine()));
    
        if (customerSpend.get(customerSpend.size()-1) == 0){
            checkUserInput = 0;
        }
    }
    

    【讨论】:

    • 谢谢,这有效,必须将 customerSpend.add(Double.parseDouble(userInput.nextDouble())); 更改为 customerSpend.add(Double.parseDouble(userInput.nextLine()));,但你让我到了那里!
    【解决方案2】:

    这是因为Scanner.nextDouble方法不读通过点击创建您的输入换行符“回车”等调用Scanner.nextLine返回读取换行符后。 P>

    当您在 Scanner.next() 或任何 Scanner.nextFoo 方法(除了 nextLine 本身)之后使用 Scanner.nextLine 时,您会遇到类似的行为。

    我的建议是在调用 userInput.nextDouble() 之后立即调用额外的 userInput.nextLine() 以读取该额外行。

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 2017-09-28
      • 2016-09-02
      • 1970-01-01
      • 2020-11-02
      • 2013-03-26
      相关资源
      最近更新 更多