Endless loop while using “try and catch ” block in

2019-01-29 04:11发布

问题:

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");
               }
        }
    }
}