我试图用一种方法不捕获任何输入(输入键),并且将除y / n外的所有内容都无效输入。我尝试了两种不同的方式(粘贴),但是我无法同时进行“输入密钥”和“错误键入y / 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;
}
答案 0 :(得分:0)
您的if陈述式在第一种情况下是错误的。您正在检查选择=SUBSTITUTE(LEFT(A2,FIND(" ",A2)-1),".","/")+SUBSTITUTE(MID(A2,FIND(" ",A2)+1,99),".",":")
或 is not equal to 'y'
是否始终为真。
更改
not equal to 'n'
收件人
if (isValid && !choice.equals("y") || !choice.equals("n"))
答案 1 :(得分:0)
我尝试了您的代码的第一次尝试。我用注释行进行了说明,该注释行包含在以下代码中;
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;
}