我希望用户输入一行文本,只要 x
不等于 numOfContestans
的值。当我运行代码时,我收到一个 InputMismatchException
。有人知道如何解决这个错误吗?
try {
int numOfContestants = scan.nextInt();
int problems = scan.nextInt();
scan.nextLine();
int x = 0;
while (x != numOfContestants) {
String input = scan.nextLine();
x++;
}
System.out.println(problems);
} catch(InputMismatchException e) {
System.out.println("Something went wrong");
}
最佳答案
您没有列出导致问题的输入。如果您尝试此输入,
3
2
line1
line2
line3
nextInt 不读取行尾的 CR/LF。第一次调用 nextLine 是空的。循环运行了正确的次数,但第一遍没有读取完整的行。读完问题后,阅读下一行。
int problems = scan.nextInt();
String input = scan.nextLine();
您还可以输入数据,使其看起来像
3
2 line1
line2
line3
然后你的代码就可以工作了。
只要正确输入整数,我就无法生成错误。
我不知道 nextLine 如何导致 TypeMismatchException。我已经运行了这段代码,并且只有在输入错误的整数时才会导致这样的错误。请提供导致错误的输入。
关于java - 使用扫描仪读取数字和文本时出现 InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562986/