Home > Enterprise >  how can I resolve try-catch issue within for loop?
how can I resolve try-catch issue within for loop?

Time:04-01

My code is almost finished. It's a guessing number game. The final piece is implementing the try-catch function so that the program catches invalid inputs like a number > 50 or typing in letters or any symbol.

Here's the code:

import java.util.*;

public class Main {
    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        //number generator
        int number = 1   (int)(50 * Math.random());

        int i, guess;
        int g = 50;


        for (i = 0; i < g; i  ) {
            try {
                System.out.println("Guess a number between 1 to 50!");

                guess = s.nextInt();


                if (guess == number) {
                    System.out.println("You got it in "   i   " tries.");
                    System.out.println("The number was: "   number);
                    break;
                } else if (guess < number) {
                    System.out.println("Too low. Try Again.");
                } else if (guess > number) {
                    System.out.println("Too high. Try Again.");
                }
            } catch (Exception e) {
                System.out.println("Oops you entered an invalid input. Try Again.");
            }
        }
    }
}

CodePudding user response:

So let's not talk about clean code, I simply want to correct your catch clause.

The main problem is, that the Scanner doesn't consume the .nextInt() if it's an invalid input.

That means after catching your exception the line is still there and will automatically be read again in your next iteration. Theoretically this would end in an infinite loop, but due to your structure your loop is limited by int g = 50;.

The only (and not that clean) solution I know is, to let the scanner simply consume the next line with .nextLine() or .next().

The solution that @Chaosfire mentioned is way better.

guess = Integer.parseInt(s.nextLine());

You will first read the line, no matter what its content is. Afterwards you try to parse the content to an Integer. In case the input is invalid the method will throw a NumberFormatException, that you catch in your catch clause.

Suggestion for loop

for(i = 0; i < g; i  ) {
  System.out.println("Guess a number between 1 to 50!");
  try {
    guess = Integer.parseInt(s.nextLine());

    if((guess < 1) || (guess > 50)) {
      throw new Exception("Integer is not in Range between 1 and 50");
    }
    if(guess == number) {
      System.out.println("You got it in "   i   " tries.");
      System.out.println("The number was: "   number);
      break;
    }
    else if(guess < number) {
      System.out.println("Too low. Try Again.");
    }
    else if(guess > number) {
      System.out.println("Too high. Try Again.");
    }
  }
  catch(Exception e) {
    i--;
    System.out.println("Oops you entered an invalid input: "   e.getMessage()   "\nTry Again.");
  }
}
  • Related