Endless loop while using “try and catch ” block inside a “while loop”

谁说我不能喝 提交于 2019-12-29 09:21:45

问题


My program has an endless loop, when I use try and catch block in a while loop.

import java.util.*;
class Try
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        while(true)
        {
            try {
                System.out.println("Enter a no ");
                int s=sc.nextInt();
            } catch(Exception e) {
                System.out.println("Invalid input try again");
            }
        }
    }
}

When I input an integer, it runs fine and asks for another input, but when I input a char, it goes for endless loop. Why is this so?


回答1:


Your program enters an infinite loop when an invalid input is encountered because nextInt() does not consume invalid tokens. So whatever token that caused the exception will stay there and keep causing an exception to be thrown the next time you try to use nextInt().

This can be solved by putting a nextLine() call inside the catch block to consume whatever input was causing the exception to be thrown, clearing the input stream and allowing the user to continue trying.




回答2:


You did not break the loop. To end the loop you need to insert

break;

wherever you would like the loop to end.




回答3:


Scanning an int does not consume the newline charackter (pressing enter). Therefor it reads the newline charackter every time and throws an InputMismatchException.

You can consume it by simply calling next() or nextLine() after your make your input.

Note: next() does only work on unix since it reads only one byte and Windows ends a line with two charackters (\r\n).




回答4:


The problem is that when you call nextInt you will screw the Scanner and so it cannot be used once nextInt caused in exception. That Scanner is not valid anymore. To get around this, you should read the content as string and cast it, when the cast operation fails, you don't have to worry about anything.

I would do it like this:

import java.util.*;
class Try
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        while(true)
        {
            try{
                System.out.println("Enter a no ");
                int s=Integer.parseInt(sc.next()); // or sc.nextLine() if you wish to get multi digit numbers 
             }catch(Exception e)
               {
                 System.out.println("Invalid input try again");
               }
        }
    }
}


来源:https://stackoverflow.com/questions/43237705/endless-loop-while-using-try-and-catch-block-inside-a-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!