I am trying to make a rock, paper, scissors game, for which I need an input from the user as his choice. Now, I also want to check whether the given input is an integer or not.
To achieve this, I used a try-catch block inside a while loop so that the loop runs until I get the desired input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number;
while (true) {
System.out.print("Enter a number : ");
try {
number = sc.nextInt();
break;
} catch (Exception e) {
System.out.println("Invalid Input");
}
}
System.out.println(number);
}
}
Now, the issue is that if the input given is wrong then it enters the catch block but after this the infinite loop is running without taking any input:
Output where wrong input is given:(https://i.stack.imgur.com/WAgIY.png)
I tried replacing the while loop with a do-while loop but the situation is unchanged.
Now, I want to know why am I encountering such a behavior.