0

所以我有一些带有扫描仪的 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)
4

1 回答 1

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.");
        }
于 2013-08-11T16:11:18.007 回答