简体   繁体   English

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

[英]What's wrong with this Scanner?

So I have some Java code with a Scanner. 所以我有一些带有扫描仪的Java代码。 What am I doing wrong as I am getting errors. 因为我遇到错误,我做错了什么。

// 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();

Errors (I am fairly new to Java, well I coded quite a bit like 4-5 years ago. but forgot): 错误(我对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)

If you type in anything other than a number (integer), your program crashes. 如果键入除数字(整数)以外的任何内容,程序将崩溃。 The following code checks if it's able to convert the input into a int. 以下代码检查它是否能够将输入转换为int。 If yes, everything is ok, otherwhise the error will be printet, but the program doesn't crash. 如果是的话,一切都很好,其他错误将是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.");
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM