0

我想让用户输入一行文本,只要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");
}
4

1 回答 1

1

您没有列出导致问题的输入。如果你尝试这个输入,

3
2
line1
line2
line3

nextInt 不读取行尾的 CR/LF。对 nextLine 的第一次调用是空的。循环运行正确的次数,但第一遍没有读取完整的行。阅读问题后,阅读下一行。

int problems = scan.nextInt();        
String input = scan.nextLine();

你也可以输入你的数据,所以它看起来像

3
2 line1
line2
line3

然后你的代码工作。

只要正确输入了整数,我就不会产生错误。

我不知道 nextLine 如何导致 TypeMismatchException。我已经运行了这段代码,如果整数输入不正确,只会导致这样的错误。请提供导致错误的输入。

于 2016-01-02T14:55:33.090 回答