# Infinite loop problem

• March 30th, 2012, 08:04 PM
jacobjc3
Infinite loop problem
Hello all, I'm working on a homework assignment involving recursion. The problem is I can't get to the recursion part because I've run into an IO problem that I can't figure out for the life of me. The whole point of the lab is doing Recursion for a binary search and I don't want help with that. I have run into a problem with getting the height/width of a rectangle from the user. If the user inputs a letter/character and not a number I get an infinite loop that is displayed as a result of catching an InputMismatchException. If anyone can give me some advice or point me in the right direction as how to fix this issue, I would greatly appreciate it.

Below is the method causing the error.

public static Rectangle getRectangle()
{
Scanner keyboard = new Scanner (System.in);

Rectangle r = new Rectangle();

System.out.print("Enter the height of the rectangle: ");
try
{
r.height = keyboard.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("You didn't enter a number. You must enter a positive integer.");
}
if (r.height <= 0)
System.out.println("You must enter a positive integer.");
System.out.print("Enter the width of the rectangle: ");
r.width = keyboard.nextInt();

return r;
}
• March 30th, 2012, 09:00 PM
KucerakJM
Re: Infinite loop problem
I take it that the method getRectangle() is used inside of a loop, possibly in the main() method? Seeing the actual loop would probably help and I find it curious that you only catch the exception for r.height and not r.width. Another thing, Scanner.next() will make the scanner advance to the next input regardless of whether or not the input is correct. In other words if there is a InputMismatchException then the scanner will just revert to the last input and not ask for anymore input.
• March 30th, 2012, 09:11 PM
jacobjc3
Re: Infinite loop problem
my apologies, I had taken out the loop before I posted the message. I didn't catch the exception for r.width because I wanted to get it right with r.height first and then just copy and paste it. I'm not quite sure what you mean by "scanner will just revert to the last input." This is the first thing that the user enters into the program. When a non-number character is entered it not only throws the error but also skips allowing the user to enter r.width.
• March 30th, 2012, 09:41 PM
KucerakJM
Re: Infinite loop problem
I suppose saying that it will revert wasn't quite right. If there is a mismatch then the Scanner won't advance to the next input and, in this case, keep using a non-integer value causing an infinite loop. You can manually skip the incorrect input by calling Scanner.next() which will let the user input something else (hopefully a correct value).