如何正确使用while循环用用户输入填充2个Arraylist?

时间:2019-02-08 21:29:00

标签: java arraylist while-loop user-input

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

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));
}

2 个答案:

答案 0 :(得分:0)

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;
    }
}

答案 1 :(得分:0)

这是因为Scanner.nextDouble方法不会在按“ Enter”键创建的输入中读取换行符,因此对Scanner.nextLine的调用在读取该换行符后返回。

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

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