0

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.

  • Hello Anubhav Jan , you can put **sc.nextLine();** inside **catch**, the buffer is empty, and the developer is happy!!. – Marce Puente Jul 27 '23 at 14:15
  • @MarcePuente Please explain this as I am really new to this. – Anubhav Jain Jul 31 '23 at 17:11
  • When there is a failure in the operation, it is necessary to empty the buffer, so that **Scanner** works well. – Marce Puente Jul 31 '23 at 18:09
  • @MarcePuente Ok so, sc.next() will clear the buffer when it is encountered in the catch block. Thank you much. Is there any way we could be connected like social media or email so I could bring my doubts directly to you. – Anubhav Jain Jul 31 '23 at 18:47

0 Answers0