File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Looping in exceptions

 
Carlos Obregon
Greenhorn
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to catch a number from a Scanner. I thought that I could catch the InputMismatchException and re-ask the user to submit another real number.

I use this but if I raise the exception it keeps in an infinite loop:



Thanks!
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because of the exception, the done variable remains false for ever. The Scanner continues to look at the token which wasn't a number, so consume that token with a call to in.next(); inside the catch. No need to do anything with that token.

Then you can enter a new token, and the loop can go round once more.
 
Rob Spoor
Sheriff
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You shouldn't use exceptions this way if there are valid checking methods available.
An improved version:
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic