简体   繁体   中英

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

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?

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.

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

break;

wherever you would like the loop to end.

In order to solve this, you need to clear the input stream otherwise same exception already caught causes make an infinite loop. By adding nextLine() inside the catch block cause to consume whatever input was causing the exception to be thrown.As a best practice like this situation it good to use hasNextInt() for checking the user input before calling the nextInt()

import java.util.*;
class Try {
    public static void main(String args[]) {
        Scanner scanner=new Scanner(System.in);
        while(true) {
            try {
                System.out.println("Enter a Number");
                int num=scanner.nextInt();
            } catch(Exception e) {
                System.out.println("Invalid input try again");
                scanner.nextLine(); // cause to consume already caught Exception 
            }
        }
    }
}

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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