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

时间:2014-06-05 22:24:00

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

这个while循环假设提示价格和ay / 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; }
    }

请帮忙吗?

3 个答案:

答案 0 :(得分:3)

这是因为每次你写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),这样就不需要||

答案 1 :(得分:1)

它要求您两次,因为您调用in.nextDouble()方法两次,一次在if语句中,另一次在下一行中。

答案 2 :(得分: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) { // <-- You are asking for the input here 
        prices.add(in.nextDouble()); // <-- and asking for the input here again.

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

只需将您的代码更改为:

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

    System.out.print("How much is the item? (If no more items, enter '0') ");

    d = in.nextDouble();

    if (d > 0) {

        prices.add(d);

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