我试图在一个方法中捕获任何输入(输入键)和无效输入( y/n除外)。我尝试了两种不同的方式(粘贴),但我不能使工作同时“输入键”和“模糊类型/n”在一起。谢谢你的帮助。
第一次尝试:
public static String askToContinue(Scanner sc) {
String choice = "";
boolean isValid = false;
while (!isValid){System.out.print("Continue? (y/n): ");
if (sc.hasNext()){
choice = sc.next();
isValid = true;
} else {System.out.println("Error! "
+ "This entry is required. Try again");
}
if (isValid && !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;
}
2nd attempt
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice;
while (true) {choice = sc.next();
//?????????????????????????????????????????????????????
if (choice.length() == 0){ System.out.println("Error! "
+ "This entry is required. Try again");
continue;
}
if (!(choice.equals("y") || choice.equals("n"))) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
continue;
}
break;
}
sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}发布于 2018-09-06 22:50:59
我第一次尝试了你的代码。我解释了注释行,它包含在下面的代码中,如;
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;
}发布于 2018-09-06 22:23:21
在第一种情况下,您的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"))https://stackoverflow.com/questions/52212464
复制相似问题