在本例中,我要求用户输入1、2或3。如果用户输入string,它应该再次询问问题。当我的代码运行时,每个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!!");
}
}
}
}
2条答案
按热度按时间hlswsv351#
我认为你的问题如下。
每次在循环中创建一个新的扫描仪
创建新扫描仪后,立即执行几个“hasnext”测试。什么都不会打出来。你可能会永远在那个圈里旋转。
整数也是double,因此即使用户键入了整数,它也将满足“if double”条件。
如果未键入整数,则永远不会读取输入,因此您将被困在输入流中的该点。你将永远循环。
流应该如下所示:
当然,这只是一个伪代码草图。
它使用异常处理作为确保输入整数的最方便方法。通过在扫描器上调用nextint(),我们假设用户要键入可转换为整数的内容。try/catch结构处理错误情况。
还有其他的写作方法;我自己的倾向是读一行并分析它。但这最接近我的初衷。
wlzqhblo2#
好吧,首先不是这样的
.hasSomething()
工作,它用来检查是否有更多的元素。因此,您应该做的是将输入读取为字符串并检查该字符串: