0

When I initialise my scanner object outside of the loop I get an infinite loop if my code enters the catch block if an invalid input (ie a non int input) is given. I think it has something to do with the Scanner object retaining that input, but I am not to sure why this is happening,.

Here is my code:

public class Random {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int age = 13;
    int guess = 0;
    do {
        System.out.print("guess age: ");
        try{
            guess = scan.nextInt();
        }
        catch (InputMismatchException i){
            System.out.println("incorrect input");
        }
        if(guess!=age) System.out.println("try again");
        else System.out.println("well done");
    }while(guess!=age);
}}

Bringing the scan object initialisation inside the try block fixes the issue:

public class Random {
public static void main(String[] args) {
    
    int age = 13;
    int guess = 0;
    do {
        System.out.print("guess age: ");
        try{
            Scanner scan = new Scanner(System.in);
            guess = scan.nextInt();
        }
        catch (InputMismatchException i){
            System.out.println("incorrect input");
        }
        if(guess!=age) System.out.println("try again");
        else System.out.println("well done");
    }while(guess!=age);
}

}

Why is this happening, and why does this not happen in the normal case when an integer value is inputted.

  • Thanks for your reply, sorry I am not quite sure what you mean by token? – Mohammad Rizwaan Sep 14 '20 at 17:37
  • 1
    For simplicity think of tokens as values separated by delimiters (by default *whitespaces*). So if user provides data like `1 true 321` then there are 3 tokens `1` `true` `321`. If Scanner will try to read token `true` using `nextInt()` exception will be thrown, but *this will not cause scanner to move to next token `321`*. Instead user can try to read that non-`int` token again (maybe with `nextBoolean()` method). But if you simply want to make Scanner *consume* that non-`int` token then let it read it (in `catch` section) using method which can accept any data like `next()` or `nextLine()`. – Pshemo Sep 14 '20 at 17:52

0 Answers0