这个 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/