• Post Reply Bookmark Topic Watch Topic
  • New Topic

Looping try/catch  RSS feed

 
Joel Christophel
Ranch Hand
Posts: 250
1
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 250
1
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 250
1
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!