如何检查用户输入是否与我需要的内容不一致



如何检查用户输入是否与我的需求不一致?在下面的代码中,如果我的用户回答3,或者什么都不回答,或者除了oui/non之外的任何事情,它仍然有效。。。即使如此,当他们输入坚果时,它也适用于";非";。。。我只想让程序工作,如果我的用户回答oui或非

public static short count;
public static void main(String[] args) {
hasKey();
}
public static void hasKey (){
System.out.print("nEst-ce que vous avez vos clé ? (oui/non)");
Scanner scan = new Scanner(System.in);
String answer = scan.nextLine();
boolean aSesClés =  answer.toLowerCase().startsWith("o"); ;
if (aSesClés) {
System.out.println("nVous avez vos clés !");
} else if (count == 10) {
System.out.println("nVous avez perdu vos clés !");
} else {
whichPlace();
}
}
public static void whichPlace() {
Scanner sc= new Scanner(System.in);
System.out.print("nQuel endroit ? ");
String quelEndroit= sc.nextLine();
System.out.print("nvous avez choisi : "+quelEndroit);
count++;
hasKey();
}
}

您可以添加一个循环,该循环将运行直到用户键入正确的内容:

final Scanner scan = new Scanner(System.in);
String answer;
// A loop that will run undefinitely
for (;;) {
System.out.print("nEst-ce que vous avez vos clé ? (oui/non)");
answer = scan.nextLine();
if (answer.equals("oui") || answer.equals("non")) {
// Exit the loop and proceed with your logic
break;
}
// Otherwise, proceed with the loop
System.out.println("Invalid answer!");
}
// Your logic when the user types a valid `answer`

最新更新