0

I think my code is doing alright except for the second catch exception which loops infinitely and I don't know why. I want it to loop again but like the first catch where after it catches an exception it loops back to the user input, but the second catch doesn't do it, it just loops infinitely.

here is what I did

import java.util.*;
import java.util.*;
class OutofBounds extends Exception{
    public OutofBounds(){
        super("Out of range");
    }
}
public class MyClass {
    public static void main(String args[]) {
      Scanner in = new Scanner(System.in);
      int count = 0;
      int min = 1;
      int max = 50;
      int ran = (int)(Math.random()*(max-min)) + min;
      int ent;
      do{
      System.out.println("Guess the number from 1 to 50.");
      try{
          do{
          ent = in.nextInt();
          count++;
          if(ent > ran && ent < max){
              System.out.println("Too high. Try again.");
          }else if(ent < ran && ent > min){
              System.out.println("Too low. Try again.");
          }else if(ent < 1 || ent > 50){
              throw new OutofBounds();
          }
          }while(ent!=ran);
          System.out.println("You got it in " + count + " attempt(s).");
      }
      catch(OutofBounds exe){
          System.out.println(exe.getMessage());
      }
      catch(InputMismatchException ex){
          System.out.println("Invalid input.");
      }
    }while(true);
    }
vromm
  • 1
  • 1
  • Aside from the issue you're having: don't throw an exception only to catch it again immediately. Handle the thing that's wrong. – Andy Turner Apr 14 '22 at 16:19
  • Oh yes greatly thank you very much. You saved me there I've been stuck with this problem for hours now. Once again thank you – vromm Apr 14 '22 at 16:26

0 Answers0