Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A try-catch method in while 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());
    }


}

1 Answers

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;
    }
}
like image 102
Chandra Sekhar Avatar answered May 10 '26 07:05

Chandra Sekhar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!