2 回答

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
我嘗試了您的代碼的第一次嘗試。我用注釋行進(jìn)行了解釋,注釋行包含在下面的代碼中,例如;
public static String askToContinue(Scanner sc) {
String choice = "";
boolean isValid = false;
while (!isValid) {
System.out.print("Continue? (y/n): ");
choice = sc.nextLine(); //to reads all line , because this cannot read with empty enter input
isValid = true;
if (choice.isEmpty()) { //this isEmpty for empty enter
System.out.println("Error! "
+ "This entry is required. Try again");
}
System.out.println(choice);
//this logic if not y or n , it will return error
if (!choice.equals("y") && !choice.equals("n")) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
isValid = false;
}
}
//sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超11個(gè)贊
您在第一種情況下的 if 語句是錯(cuò)誤的。您正在檢查是否選擇is not equal to 'y'
或 not equal to 'n'
將始終為真。
改變
if (isValid && !choice.equals("y") || !choice.equals("n"))
到
if (isValid && !choice.equals("y") && !choice.equals("n"))
添加回答
舉報(bào)