这是一个基于控制台的小问答游戏的基本设置。答案已编号。我希望玩家给出答案号码。如果输入不是数字,那么我的程序应该发出警告,并等待正确的输入。 相反,我得到的东西(在插入不是数字的东西之后)是一个无限循环,询问问题并再次提出答案。
public static void main(String[] args) {
boolean quizActive = true;
while(quizActive) {
presentQuestion();
presentAnswers();
Scanner s = new Scanner(System.in);
if (s.hasNext()) {
String choice = s.next();
if (!NumberUtils.isNumber(choice)) {
presentText("Please insert the answer number.");
} else {
System.out.println("You made a choice!");
checkAnswer(choice);
quizActive = false;
}
s.close();
}
}
}
我在这里做错了什么?
答案 0 :(得分:2)
如果您不希望每次在循环外移动presentQuestion()
和presentAnswers()
时提出问题和答案。
但主要问题是您关闭Scanner
。
移除s.close();
并将Scanner s = new Scanner(System.in);
移出循环。
答案 1 :(得分:1)
我真的不明白使用扫描仪来获取用户输入。
扫描仪类非常适合处理具有CSV等已知结构的平面文件的结构化输入。
但是用户输入需要处理所有人类的不完美。在Integer.parseInt()
失败后,您获得的唯一优势就是不需要以scanne.nextInt()
为代价来处理未清除的输入...
那么为什么不将InputStreamReader
与其他人建议的循环一起使用呢?
答案 2 :(得分:0)
你在一个循环中开始你的测验,由你的quizActive布尔值调节。这意味着每次循环重新开始时都会调用方法presentQuestion()
和presentAnswers()
。
如果您不输入数字而不是字符,例如,您的程序将运行presentText("Please insert the answer number.")
并再次启动循环。当它再次启动循环时,它将调用方法presentQuestion()
和presentAnswers()
。
要停止此操作,您可以围绕输入序列执行另一个循环。你的Scanner s = new Scanner(System.in)
也应该在循环之外。并且您不应该在第一次输入后立即关闭扫描仪,然后再打开它!
如果你想要一个代码示例,请告诉我:)
答案 3 :(得分:0)
这里有一个例子:
public class Application {
public static void main(String [] args) {
System.out.println("Please insert the answer number. ");
while (true) {
try {
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
System.out.println("You made a choice!");
checkAnswer(choice);
break;
} catch (Exception e) {
System.out.println("Invalid Number, Please insert the answer number ");
}
}
}
}