2

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?

3
  • Does it keep printing stuff or it just hangs? Commented Apr 5, 2017 at 17:21
  • what will it print in the endless loop Commented Apr 5, 2017 at 17:23
  • it goes to like infinity loop, it keep printing "Enter a no " "Invlide input try again" Commented Apr 5, 2017 at 17:23

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

using a break ststement will exit the program, i don't want to exit,
Sorry, I discovered that your scanner is what is the issue. I wasn't thinking clearly, Try it out. I am confident that I have the right answer.
next() will probably not work on Windows since it reads only one byte while Windows uses two charackters to end an line ( \r\n ).
@DonFoumare Thanks.
@flakes LOL! Yeah, run out of memory or slow down the inout.
|
1

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

break;

wherever you would like the loop to end.

1 Comment

actually i want to use the same logic in a another program, and i don't want to break the loop, i want it to send the curser back input section after printing the error (catch block), to re enter the data, but apart from that it goes to endless loop...!!
1

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 
            }
        }
    }
}

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.