2 回答
TA贡献1900条经验 获得超5个赞
我尝试了您的代码的第一次尝试。我用注释行进行了解释,注释行包含在下面的代码中,例如;
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贡献1775条经验 获得超11个赞
您在第一种情况下的 if 语句是错误的。您正在检查是否选择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"))
添加回答
举报