简体   繁体   English

循环中的Java catch语句不起作用

[英]Java catch statement in loop does not work

When I run th code, and say input 2.5, the output I get is: 当我运行代码并说输入2.5时,我得到的输出是:

2.5, 4 times "error", and 5. 2.5,4次“错误”,和5。

It means that the computer goes through the catch statement every time, instead of asking for input every time it loops through the while loop and enters the try block. 这意味着计算机每次都会通过catch语句,而不是每次循环while循环并进入try块时都要求输入。

public static void main(String[] args)
{
    Scanner s1 = new Scanner(System.in);
    int n = 0;
    while(n<5)
    {
        try
        {
            int grade = s1.nextInt();
            System.out.println(grade);
        }
        catch(Exception e)
        {
            System.out.println("error");
        }
        n++;
    }
    System.out.println(n);
}

When you enter "2.5", nextInt() consumes the 2 . 输入“2.5”时, nextInt()消耗2 The next thing being scanned by the very same nextInt() will be . 下一件事就是由同一个nextInt()扫描. and that cannot be successfully scanned by nextInt() , so you get the error. 并且nextInt()无法成功扫描,因此您收到错误。 nextInt() can only be used to scan int numbers, if you want to scan fractions like 2.5 , you need nextDouble() . nextInt()只能用于扫描int数字,如果你想扫描像2.5这样的分数,你需要nextDouble()

By the way, the exception objects hold useful information. 顺便说一下,异常对象包含有用的信息。 If you do this, you're just hiding the error information: 如果你这样做,你只是隐藏错误信息:

catch (Exception e) {
    System.err.println(error):
}

Instead do this: 而是这样做:

catch (Exception e) {
    e.printStackTrace();
}

And don't mix System.out and System.err . 并且不要混用System.outSystem.err System.out is for the normal program output but not for logging, debug, info, warning, error or such messages. System.out用于正常程序输出,但不用于记录,调试,信息,警告,错误或此类消息。 Those should go to System.err . 那些应该去System.err

Basically, there is a "cursor" that points to the next character of your input line that a Scanner will read. 基本上,有一个“光标”指向Scanner将读取的输入行的下一个字符。 If the input line looks like 如果输入行看起来像

bad input

the cursor starts before the b . 光标在b之前开始。 If you call nextInt() , the Scanner will throw an exception, because b can't be the start of an integer. 如果调用nextInt() ,则Scanner将抛出异常,因为b不能是整数的开头。 But the cursor stays in the same place . 但光标停留在同一个地方 So next time you call nextInt() , the same error will happen all over again. 所以下次调用nextInt() ,会再次发生同样的错误。

You need to do something that will "consume" the bad input so that the cursor will move. 你需要做一些“消耗”坏输入的东西,以便光标移动。 s1.nextLine() , as in almas' answer, will consume the entire rest of the line. s1.nextLine() ,就像在almas的回答中一样,将消耗整个行的其余部分。

If the input is 如果输入是

2.5

nextInt() will throw an exception because 2.5 is not an integer. nextInt()将抛出异常,因为2.5不是整数。 Once again, the cursor stays in the same place, so the error will keep coming up, unless you do something to consume the 2.5 . 再一次,光标停留在同一个地方,所以错误会不断出现,除非你做了什么来消耗2.5 If you want the program to actually read 2.5 , then don't use nextInt() since 2.5 is not an integer. 如果你想让程序实际读取2.5 ,那么不要使用nextInt()因为2.5不是整数。

According to the documentation: 根据文件:

This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. 如果下一个标记无法转换为有效的int值,则此方法将抛出InputMismatchException,如下所述。 If the translation is successful, the scanner advances past the input that matched. 如果翻译成功,扫描仪将超过匹配的输入。

This means that if the translation is NOT successful, the scanner does not advance past the input. 这意味着如果翻译不成功,扫描仪不会超过输入。 It keeps trying to translate .5 in every iteration. 它不断尝试在每次迭代中翻译.5。

You can get the result I assume you expect by adding s1.next() in your catch statement to clear the token in the Scanner: 您可以通过在catch语句中添加s1.next()来清除Scanner中的标记,从而得到我假设您期望的结果:

public static void main(String[] args)
{
    Scanner s1 = new Scanner(System.in);
    int n = 0;
    while(n<5)
    {
        try
        {
            int grade = s1.nextInt();
            System.out.println(grade);
        }
        catch(Exception e)
        {
            **s1.next();**
            System.out.println("error");
        }
        n++;
    }
    System.out.println(n);
}

And as many have already mentioned, output all possible information from exception! 正如许多人已经提到的那样,从异常输出所有可能的信息!

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

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