【问题标题】:java.util.InputMismatchException when reading simple value读取简单值时出现 java.util.InputMismatchException
【发布时间】:2018-04-30 10:02:27
【问题描述】:

我在这里读过类似的答案,但我仍然想不出这里发生了什么。我有以下 sn-p:

 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

【问题讨论】:

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


    【解决方案1】:

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

    nextLine() 调用将在 int 之后使用换行符:

    text = scanner.nextLine();
    

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

    value = scanner.nextInt();
    

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

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

    【讨论】:

      猜你喜欢
      • 2015-05-13
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多