【发布时间】:2021-03-15 00:37:15
【问题描述】:
在这种情况下,我要求用户输入 1,2 或 3。如果用户输入字符串,它应该再次提问。当我的代码运行时,每个 if 语句都在运行,而我想运行一个特定的 if 语句。如果有人可以帮助我,那将是一个巨大的帮助。
String question = "What is the color of banana? Write 1,2 or 3. Choose one of the following:";
String answerOne = "1. yellow";
String answerTwo = "2. red";
String answerThree = "3. blue";
while(true){
System.out.println(question + "\n" + answerOne + "\n" + answerTwo + "\n" + answerThree);
Scanner input = new Scanner(System.in);
if (input.hasNext()) {
System.out.println("Please select a NUMBER between 1 and 3.");
}
if (input.hasNextDouble()) {
System.out.println("Please select a NUMBER between 1 and 3.");
}
if (input.hasNextInt()) {
int x = input.nextInt();
if (x == 1) {
System.out.println("Congratulations!! your answer is correct");
break;
}
if (x == 2 || x == 3) {
System.out.println("Sorry!! the correct answer is" + answerOne);
break;
}
if (x > 3) {
System.out.println("Please choose the correct answer!!");
}
}
}
}
【问题讨论】:
标签: java if-statement input while-loop integer