Java 什么';这台扫描仪怎么了?

Java 什么';这台扫描仪怎么了?,java,java.util.scanner,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.

所以我有一些带扫描器的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年前,但忘记了):


如果键入的不是数字(整数),则程序将崩溃。下面的代码检查是否能够将输入转换为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.");
        }

您没有传递可以转换为int的值。您从用户输入传递的是什么?@RohitJain,我不明白您的意思,抱歉。您能进一步解释一下吗?您需要传入一个有效的整数…@Script47:此错误意味着:您告诉我读取一个int,但下一个标记根本不是int。例如,如果键入“hello”,您将得到此异常,因为hello不是int。5、78甚至765都可以。@JBNizet,感谢您对此错误的清晰解释。我阅读了“InputMismatch”部分,意识到可能是这样的。感谢您的回答,我正要学习错误处理,您将其包括在本示例中,非常感谢。我想,我也尝试过,但它说等待。只要我能,我一定会的!谢谢,伙计。:)最后一件事,为什么是System.err而不是System.out?好吧!我喜欢将输出(不是主应用程序流的一部分)打印到错误控制台上(例如,它们在eclipse控制台中显示为红色),以便在滚动程序的日志输出时对我更可见。我知道我说了最后一件事,但我需要导入错误,这正常吗?这将是最后一件事,但如果返回自定义错误,我该如何让用户再次执行输入部分?是的,这是正常的。如果缺少导入,则编译器将找不到类InputMismatchException。您可以围绕try-catch块执行循环,并在用户输入有效数字后立即中止循环。
        // 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.");
        }