Skip to main content

Looping "try/catch" help

2 replies [Last post]
joelamos
Offline
Joined: 2012-04-21
Points: 0

When I run the below method and intentionally input a letter when a number is expected, I get a never-ending loop that doesn't prompt for more input. Why?

private static int intInput() //Asks the user for an int and returns the input.
  {
Scanner genericIntScan = new Scanner(System.in);
    boolean itsAnInt = false;
    int genericInt = 0;
   
   while(itsAnInt==false)
   {
    try
      {
      genericInt = genericIntScan.nextInt();
      itsAnInt = true;
      }
    catch(InputMismatchException ime)
      {
      System.out.println("\nYou're supposed to type in a number. Try again.");
      itsAnInt = false;
      }
    }
   return genericInt;
}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
egc2224
Offline
Joined: 2006-02-17
Points: 0

have you tried adding a print statement inside the try block to see how far down that block the code is going. sounds like it is going into that block and never coming out. if it is coming out of the try block into the catch block then you are setting itsAnInt to false which is causing the loop to complete again. another thing i would catch is to make sure you are catching the error type you think you are catching. if a different type of error it getting thrown then that might be causing problems. that's three things you might look into further.

teleporter
Offline
Joined: 2012-05-14
Points: 0

Thanks for the answer.