How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner

scanner catch (inputmismatchexception)
how to handle infinite loop in java
java scanner error handling
try-catch loop java
infinite try-catch
wrong input exception java
catch input exception java
java try-catch in while loop

So, I'm getting stuck with this piece of code:

import java.util.InputMismatchException;
import java.util.Scanner;

public class ConsoleReader {

    Scanner reader;

    public ConsoleReader() {
        reader = new Scanner(System.in);
        //reader.useDelimiter(System.getProperty("line.separator"));
    }

    public int readInt(String msg) {
        int num = 0;
        boolean loop = true;

        while (loop) {
            try {
                System.out.println(msg);
                num = reader.nextInt();

                loop = false;
            } catch (InputMismatchException e) {
                System.out.println("Invalid value!");
            } 
        }
        return num;
    }
}

and here is my output:

Insert a integer number: Invalid value! Insert a integer number: Invalid value! ...

As per the javadoc for Scanner:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

That means that if the next token is not an int, it throws the InputMismatchException, but the token stays there. So on the next iteration of the loop, reader.nextInt() reads the same token again and throws the exception again. What you need is to use it up. Add a reader.next() inside your catch to consume the token, which is invalid and needs to be discarded.

...
} catch (InputMismatchException e) {
    System.out.println("Invalid value!");
    reader.next(); // this consumes the invalid token
} 

java: inputmismatchexception: entering into infinite loop?, question already has answers here: How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner (5 answers). Home » Java » How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner

What I would do is read in the whole line using Scanner.nextLine(). Then create another scanner that reads the returned string.

String line = reader.nextLine();
Scanner sc = new Scanner(line);

This would make your sample function something like this:

  public int readInt(String msg) {
        int num = 0;
        boolean loop = true;

        while (loop) {
            try {
                System.out.println(msg);
                String line = reader.nextLine();
                Scanner sc = new Scanner(line);
                num = sc.nextInt();   
                loop = false;
            } catch (InputMismatchException e) {
                System.out.println("Invalid value!");

            } 
        }
        return num;
    }

This way you have one scanner that gets the input and one that validates it so you don't have to worry about reader caring if they input the correct form of input.

How to Catch Exceptions in Java, How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner (5 answers). Closed 4 years ago. I'm trying to make sure that the  The exception itself thrown before your code reaches assignment loop = false; To be precise, the exception is thrown in previous statement which is num = reader.nextInt(); When exception thrown, value of 'loop' variable is 'true' but your code jumps to catch block and then repeats the while-do.

The guard of your while-do is 'loop' variable.

The exception itself thrown before your code reaches assignment loop = false; To be precise, the exception is thrown in previous statement which is num = reader.nextInt();

When exception thrown, value of 'loop' variable is 'true' but your code jumps to catch block and then repeats the while-do. This while-do will never stop because next iteration will throw an exception again, jumps to catch block again and so on.

To terminate this while-do, you need to guard your while-do with another logical thing such as :

  1. Exit when reader gets non-int character
  2. Exit when EOF

This can be done in catch block or some other lines. But precise solution depends on your specifications.

Help on a Simple Try Catch Program : javahelp, Whenever you use a statement that might throw an exception in Java, you The next method must be called in the catch block to dispose of the user's invalid input the input value in the Scanner's input stream if an InputMismatchException is thrown throws an exception, and displays an error message in an infinite loop. How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner (5 answers) Closed 2 years ago . Help, I am completely new to java and I am trying to create a loop that will ask for an input from the user which is to be a number.

You may also try this:

   public int readInt(String msg) {
        int num = 0;
        try {
            System.out.println(msg);
            num = (new Scanner(System.in)).nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Invalid value!");
            num = readInt(msg);
        } 
        return num;
    }

6. Exceptions, r/javahelp: General subreddit for helping with **Java** code. For some reason it's creating an infinite loop and none of us can figure out what's wrong. In the catch block, call console.next() to consume the invalid input before looping. throws an InputMismatchException, the scanner will not pass the token that caused  try/catch with InputMismatchException creates infinite loop is to define Scanner input = new Scanner(System.in); inside the try block, this will create a new

package nzt.nazakthul.app;

import java.util.*;

public class NztMainApp {

    public static void main(String[] args) {
    ReadNumber readObj = new ReadNumber();
    readObj.readNumber();
    }

}

class ReadNumber {
int no;

    int readNumber() {
    Scanner number = new Scanner(System.in);
    int no=0;
    boolean b=true;
    do {

        try {
            System.out.print("Enter a number:\t");
            no = number.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("No Number");
            //e.printStackTrace();

            b=false;
        }

    }

    while (b);
    return no;

    }

}

Personally i use BufferedReader and InputStreamReader to read String and check if is a number or not, but with scanner is less code. The code is checked and run ok.

no such element exception (Beginning Java forum at Coderanch), In many cases it is useful to generate exceptions explicitly using the throw statement. InputMismatchException (scanner read) java.util.regex. minimalistic style of putting only the exception-causing statement in a try/catch block: go past the invalid input, "xx" and so if you do not skip the line, you'll be in an infinite loop. Quand un scanner lance une InputMismatchException, le scanner ne pas passer le jeton qui a causé l'exception, de sorte qu'il peut être récupéré ou sauté par un autre méthode. cela signifie Que si le prochain jeton n'est pas un int , il lance le InputMismatchException , mais le jeton reste là.

How to catch exception generated by user inputting number over , Input mismatch exception is a particularly bad exception to catch, since I /how-​to-handle-infinite-loop-caused-by-invalid-input-using-scanner. How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner Tags ajax android angular api button c++ class database date dynamic exception file function html http image input java javascript jquery json laravel list mysql object oop ph php phplaravel phpmysql phpphp post python sed select spring sql string text

//creating scanner object for user input return true under very specialised circumstances caused by inappropriate use of integer literals. //Progress: Something is causing an infinite loop on the "enter first number" to catch (​InputMismatchException e) //not catching, fix later. {. //inform user of invalid input. Your program enters an infinite loop when an invalid input is encountered because nextDouble() 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 read a double.

Which means after you catch the exception, log it, and go back to the beginning of the loop again that non-int input is still in the scanner, waiting to be parsed. So when you call nextInt () again, the exception gets thrown again. You need to call something other than nextInt ()

Comments
  • Do consider getting rid of the variables loop and num and instead use while (true) { try { ....; return reader.nextInt(); } catch {....} }
  • +1 Note to readers: depending on the circumstance, you may want to use nextLine() instead of next() so that input like this has spaces in it doesn't trigger multiple exceptions.