I have a loop with a try-catch statement in it that is giving me issues., here is the code for it:
Expand|Select|Wrap|Line Numbers
- do
- {
- System.out.print("Number of courses being entered: ");
- try
- {
- numCourses = userIn.nextInt();
- failed = false;
- }
- catch (InputMismatchException ime)
- {
- failed = true;
- }
- if (numCourses < 1 || numCourses > 8 || failed)
- System.out.println("Invalid Number Entered. Please enter a valid number between 1 and 8.");
- }
- while (numCourses < 1 || numCourses > 8 || failed);
When I run this, I am given the first prompt, asking me num of courses, fine, I enter an integer, and the rest of the program works just fine. If I enter a letter, or any other non-numerical character, it throws and exception, which it catches, and sets failure to true. It then goes to the if statement, prints the line because failure is true, and then goes to the while(), finds that failure is true, so it goes back to the top, but it DOES NOT ask for another input, it skips the entire try-catch statement, and does the if statement again, giving me an infinite loop.
So, my question: Why doesn't it redo the try-catch statement once I've been throught the loop once. Why is it skipping try-catch every subsequent run throught the loop, going straight to the if statement?
Much appreciated, try-catch is still new to me, so it's probaly some property of try-catch I don't know about...
Thanks again!