读取简单值时java.util.InputMismatchException

时间:2017-11-16 18:37:16

标签: java exception exception-handling io java.util.scanner

我在这里读过类似的答案,但我仍然无法思考这里发生了什么。我有以下代码段:

 public static void main(String [] args) {
    Scanner scanner = new Scanner(System.in);

    String text = null;
    int option, value = 0;

    System.out.println("1. Cipher - 2. Decypher");
    option = scanner.nextInt();

    switch (option) {
        case 1:
            text = scanner.nextLine();
            value = scanner.nextInt();
            break;

        case 2:
            text = scanner.nextLine();
            value = scanner.nextInt();
            break;
    }
    System.out.println("you have entered " + text);
    System.out.println("you have entered " + value);
}

因此,如果输入1,则可以编写一个String,然后编写一个int。简单,对吧?

然后,为什么我在键入" 1"后输入此输出,然后输入" hello"?

1. Cipher - 2. Decypher
1
hello
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at phd.cml.PruBorrar.main(PruBorrar.java:19)

Process finished with exit code 1

1 个答案:

答案 0 :(得分:1)

scanner.nextInt()方法只返回下一个int,它不会消耗你在int之后输入的换行符。

nextLine()调用将在int:

之后使用换行符
text = scanner.nextLine();

然后这将尝试使用“hello”并抛出InputMismatchException:

value = scanner.nextInt();

所以基本上你只需要在调用scanner.nextLine()后添加额外的scanner.nextInt()

这更彻底地解释了它:https://www.reddit.com/r/javahelp/wiki/scanner