java - 为什么它连续提示我两次?

标签 java arraylist while-loop java.util.scanner prompt

这个 while 循环应该提示输入价格和 y/n,如果价格 = 0 则结束。但是,当我运行代码时,它会询问价格,接受价格,转到空行,然后我在问我下一个问题之前必须再次输入号码。对于第二个问题,我只需输入一次。

当我打印价格数组时,该值是我第二次输入的数字。

    int keepGoing = 1;
    while (keepGoing > 0) {

        System.out.print("How much is the item? (If no more items, enter '0') ");
        if (in.nextDouble() > 0) {
            prices.add(in.nextDouble());

            System.out.print("Is the item a pet? (Y or N) ");
            String input = in.next();
            if (new String("Y").equals(input) || new String("y").equals(input)) {
                isPet.add(true);
            }
            else { isPet.add(false); }
        }
        else { keepGoing = 0; }
    }

请帮忙?

最佳答案

这是因为每次编写 in.nextDouble() 时,用户都需要在扫描仪中输入一些内容。相反,您应该将输入存储在临时变量中:

    Double input = in.nextDouble(); // Keep the input in this variable
    if (input > 0) {                // You can use it on each of these lines
        prices.add(input);          // so that the user doesn't have to type it twice.

        System.out.print("Is the item a pet? (Y or N) ");
        String input = in.next();
        if (new String("Y").equals(input) || new String("y").equals(input)) {
            isPet.add(true);
        }
        else { isPet.add(false); }
    }
    else { keepGoing = 0; }

一点旁注:keepGoing 可能应该是 boolean 而不是 int

此外,您还可以使用 new String("Y").equalsIgnoreCase(input) 这样就不需要 ||

关于java - 为什么它连续提示我两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24071194/

相关文章:

java - 如何在事务期间将只读 hibernate session 转换为写入(主/从数据库)

java - volatile 的目的/优点

java - 如何将对象 ArrayList 中的文本设置到 TextView 中?

PHP 如果文件夹存在为每个子文件夹做一个循环

java - 通过蓝牙从 Arduino 获取奇怪的数据到 Android

java - Eclipse(Java): Central "treat warnings as errors"

java - 在 Android 中使用 `Calendar` 指定日期时间范围

java - 找不到 ArrayList

java - While 循环不会重新运行程序,仅询问是否要再次循环

c++ - 陷入无限循环