[英]Program doesnt wait to ask for user input
I'm having an issue where my program is skipping a prompt for user input. 我的程序在跳过提示用户输入时遇到问题。 The relevant code is below:
相关代码如下:
System.out.format("Purchase price is $" + "%.2f%n", sum);
System.out.println("Proceed to payment? (y/n) ");
String proceed = keyboard.nextLine();
while(!proceed.equals("n") && (!proceed.equals("y"))) {
System.out.println("Invalid response. Try again.");
System.out.println("Proceed to payment? (y/n) ");
proceed = keyboard.nextLine();
if (proceed.equals("n")) {
System.out.println("Come back next time, " + name + ".");
System.exit(0);
}
else if (proceed.equals("y")) {`
The output should pause at: 输出应在以下位置暂停:
Purchase price is $x.00 购买价格为$ x.00
Proceed to payment? 继续付款? (y/n)
(是/否)
But instead outputs: 但改为输出:
Purchase price is $x.00 购买价格为$ x.00
Proceed to payment? 继续付款? (y/n)
(是/否)
Invalid response. 无效的回应。 Try again.
再试一次。
Proceed to payment? 继续付款? (y/n)
(是/否)
Would anyone be able to tell me why its ignoring the first scanner prompt? 谁能告诉我为什么它忽略了第一个扫描仪提示?
EDIT: The code works in isolation, the problem is somewhere else inside the program. 编辑:代码是隔离工作的,问题出在程序内部的其他地方。 When I figure it out I'll report back.
当我弄清楚时,我会报告。
This logic in the while loop condition is wrong while循环条件中的这种逻辑是错误的
while(!proceed.equals("n") && (!proceed.equals("y"))) {
must be 一定是
while(!proceed.equals("n") || (!proceed.equals("y"))) {
if you want to keep your logic with the AND condition then MOVE the payment out of the while so that can work 如果您想保持AND条件的逻辑,那么请暂时取消付款,这样就可以了
while (!proceed.equalsIgnoreCase("n") && (!proceed.equalsIgnoreCase("y"))) {
System.out.println("Invalid response. Try again....");
proceed = keyboard.nextLine();
}
if (proceed.equalsIgnoreCase("n")) {
System.out.println("Come back next time, " + name + ".");
System.exit(0);
} else if (proceed.equalsIgnoreCase("y")) {
System.out.println("now we are going to pay, " + name + "." + sum);
System.exit(0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.