2

I am trying to make a program where the user will input a random integer/number. But the main issue is, if users accidentally input a String, I want them to be informed and also I want them to ask to input again by asking them again. But in my code, I cant loop my catch.

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int answer = 28;
    int attempts = 0;
    
    System.out.println("Guess a Number 1 - 50:");
    
    while(true) {
      try {
        int input = scan.nextInt();
        scan.nextLine();
        if(input > answer) {
          System.out.println("Too Big");
          System.out.println("Guess a Number 1 - 50:");
        } else if (input < answer) {
          System.out.println("Too Small");
          System.out.println("Guess a Number 1 - 50:");
        } else if (input == answer ) {
          System.out.println("Congrats!");
        } 
      } catch (InputMismatchException e) {
        System.out.println("Numbers only");
        System.out.println("Guess a Number 1 - 50:");
      } 
    }
}
João Dias
  • 16,277
  • 6
  • 33
  • 45
Pablo Job
  • 29
  • 4
  • 2
    Try moving that `nextLine()` to within the catch -- that way, you only fast-forward past the line if the current input wasn't a valid int. – yshavit Nov 08 '21 at 04:59
  • 1
    Does this answer your question? [Catching exception and requesting user to re-enter input](https://stackoverflow.com/questions/47137783/catching-exception-and-requesting-user-to-re-enter-input) – Nora Na Nov 08 '21 at 04:59

3 Answers3

0

Remove the scan.nextLine(); from your try block and then place a scan.skip(".*"); in your catch block. This will skip the invalid input (.* matches basically any character). Additionally, you may replace the last else if with a simple else since that is the only possibility left. Having said that, try the following:

public static void main(String[] args) throws IOException {
    Scanner scan = new Scanner(System.in);

    int answer = 28;
    int attempts = 0;

    System.out.println("Guess a Number 1 - 50:");

    while(true) {
        try {
            int input = scan.nextInt();
            if(input > answer) {
                System.out.println("Too Big");
                System.out.println("Guess a Number 1 - 50:");
            } else if (input < answer) {
                System.out.println("Too Small");
                System.out.println("Guess a Number 1 - 50:");
            } else {
                System.out.println("Congrats!");
            }
        } catch (InputMismatchException e) {
            System.out.println("Numbers only");
            System.out.println("Guess a Number 1 - 50:");
            scan.skip(".*");
        }
    }
}
João Dias
  • 16,277
  • 6
  • 33
  • 45
0

You are asking for a reason

This code has an infinite loop when invalid input is encountered because nextInt() does not take invalid tokens, So the invalid token stay there in the scanner because it is not consumed due to the exception, keep causing an exception to be thrown the next time you try to read an int because nextLine is never reached due to the exception.

This can be solved by putting the nextLine() inside the catch block to consume whatever input was causing the exception to be thrown, clearing the input stream and allowing the user to input something again.

    public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int answer = 28;
    int attempts = 0;
    
    System.out.println("Guess a Number 1 - 50:");
    
    while(true) {
      try {          
        int input = scan.nextInt();
        scan.nextLine();  // never reached when exception is thrown
        if(input > answer) {
          System.out.println("Too Big");
          System.out.println("Guess a Number 1 - 50:");
        } else if (input < answer) {
          System.out.println("Too Small");
          System.out.println("Guess a Number 1 - 50:");
        } else if (input == answer ) {
          System.out.println("Congrats!");
        } 
      } catch (InputMismatchException e) {
        scan.nextLine(); // This skips the invalid token 
        System.out.println("Numbers only");
        System.out.println("GuessNumber 1 - 50:");
      } 
    }
}
The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
-1

You should try this code, It will work perfectly for your requirement...


     public static void main(String[] args) {
        int answer = 28;
        System.out.println("Guess a Number 1 - 50:");
        boolean condition = true;
        while (condition) {
            try {
                    Scanner scan = new Scanner(System.in);
                    int input = scan.nextInt();
                    scan.nextLine();
                    if (input > answer) {
                        System.out.println("Too Big");
                        System.out.println("Guess a Number 1 - 50:");
                    } else if (input < answer) {
                        System.out.println("Too Small");
                        System.out.println("Guess a Number 1 - 50:");
                    } else {
                        System.out.println("Congrats!");
                        condition=false;
                    }
            } catch (Exception e) {
                    System.out.println("Numbers only");
                    System.out.println("Guess a Number 1 - 50:");
            }
        }
    }

  • This answer could be improved if you provided some explanation - what have you fixed, and why do you think this will fix the original problem? Also, I'm not sure whether you've tested it. – Dawood ibn Kareem Nov 08 '21 at 05:05
  • Sorry for not testing fully, I have changed some part of code and now it is working perfectly as requirement, please go through it, thank you for your feed back. – Prashanth Billa Nov 08 '21 at 05:41
  • You still haven't provided any kind of explanation. Also, are you _really sure_ it's working when the user enters something that isn't a number? – Dawood ibn Kareem Nov 08 '21 at 17:42