Java – A try-catch method in while loop

javatry-catchwhile-loop

I have this code, and I want to put the try-catch inside a while loop. The logic would be, "while there is an input error, the program would keep on asking for a correct input". How will I do that? Thanks in advance.

public class Random1 {

  public static void main(String[] args) {

    int g;

    Scanner input = new Scanner(System.in);
    Random r = new Random();
    int a = r.nextInt(10) + 1;


    try {
        System.out.print("Enter your guess: ");
        g = input.nextInt();
        if (g == a) {

            System.out.println("**************");
            System.out.println("*  YOU WON!  *");
            System.out.println("**************");
            System.out.println("Thank you for playing!");

        } else if (g != a) {
            System.out.println("Sorry, better luck next time!");
        }
    } catch (InputMismatchException e) {
        System.err.println("Not a valid input. Error :" + e.getMessage());
    }


}

Best Solution

Here I have used break and continue keyword.

while(true) {
    try {
        System.out.print("Enter your guess: ");
        g = input.nextInt();
        if (g == a) {

            System.out.println("**************");
            System.out.println("*  YOU WON!  *");
            System.out.println("**************");
            System.out.println("Thank you for playing!");

        } else if (g != a) {
            System.out.println("Sorry, better luck next time!");
        }
        break;
    } catch (InputMismatchException e) {
        System.err.println("Not a valid input. Error :" + e.getMessage());
        continue;
    }
}