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.