aspose file tools
The moose likes Beginning Java and the fly likes Looping try/catch Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Looping try/catch" Watch "Looping try/catch" New topic
Author

Looping try/catch

Joel Christophel
Ranch Hand

Joined: Apr 20, 2011
Posts: 119

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?

Rene Ott
Greenhorn

Joined: Apr 20, 2012
Posts: 8

Your condition is to loop until itsAnInt ==true, lets start looping.
You enter character and then set itsAnInt =true, but because you entered character you catch exception.

after you catch exception you set itsAnInt = false. Program's next step is to check while loop's condition, which was continue until itsAnInt ==true, but we had itsAnInt = false.
Joel Christophel
Ranch Hand

Joined: Apr 20, 2011
Posts: 119

Well, I tried removing the last "itsAnInt = false" and it didn't change a thing. I also know that itsAnInt is never made true when a non-numerical character is typed in. Here's the code I used to test that:
Joel Christophel
Ranch Hand

Joined: Apr 20, 2011
Posts: 119

I found the answer to my problem elsewhere and felt I should share it here. nextLine() is needed to clear the Scanner. Here's the code:
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Looping try/catch
 
Similar Threads
Initial variables before a try\catch block
IOException
Looping in exceptions
How to reiterate a do while loop after an exception is caught, run time error handling issue
Scanner class