[英]Program doesnt wait to ask for user input
我的程序在跳過提示用戶輸入時遇到問題。 相關代碼如下:
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")) {`
輸出應在以下位置暫停:
購買價格為$ x.00
繼續付款? (是/否)
但改為輸出:
購買價格為$ x.00
繼續付款? (是/否)
無效的回應。 再試一次。
繼續付款? (是/否)
誰能告訴我為什么它忽略了第一個掃描儀提示?
編輯:代碼是隔離工作的,問題出在程序內部的其他地方。 當我弄清楚時,我會報告。
while循環條件中的這種邏輯是錯誤的
while(!proceed.equals("n") && (!proceed.equals("y"))) {
一定是
while(!proceed.equals("n") || (!proceed.equals("y"))) {
如果您想保持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.