这款扫描仪出了什么问题?

时间:2013-08-11 16:07:20

标签: java java.util.scanner

所以我有一些带有扫描仪的Java代码。当我遇到错误时,我做错了什么。

// Creates a "scanner" for the input
Scanner readInput = new Scanner(System.in);

// Print out random integer and open close message.
System.out.println("Printing Random Numbers between 1-200: ");
int guess = readInput.nextInt();

错误(我对Java很新,我的编码很像4-5年前。但是忘了):

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at main.files.mian.main(mian.java:30)

1 个答案:

答案 0 :(得分:2)

如果输入数字(整数)以外的任何内容,程序将崩溃。以下代码检查它是否能够将输入转换为int。如果是的话,一切正常,其他错误将是printet,但程序不会崩溃。

        // Creates a "scanner" for the input
        Scanner readInput = new Scanner(System.in);

        // Print out random integer and open close message.
        System.out.println("Printing Random Numbers between 1-200: ");
        try {
            int guess = readInput.nextInt();
        } catch (InputMismatchException e) {
            System.err.println("You didn't enter a number.");
        }