• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Read input from user until an input is valid

 
Nelson Sam
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to read an input from the user.If the input is anything other than number the exception should be thrown.And should prompt the user to again input until the input is a number.

I have done the code this far.



Appreciate for all your help.
 
Martin Vanyavchich
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should try to put you number-getting logic in a loop, that would exit when you are satisfied with the users input.
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can suggest, put the try/catch statements in a method, and call that method from the main() method. In this method, include try, catch, and finally, and if invalid inputs, give warning to the user from your catch method, and eventually you'll come to the finally block, so in that block, call the method again, and Check for END(some thing to end the program) input from the user, and if he wants to end, use a force exit from the try block(like System.exit())!
 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe this might help you! [=



C ya!
 
Nelson Sam
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Abimaran Kugathasan .I really like your approach.Will try and let you know.

@Hebert Coelho-Thanks for the code.Works really fine.Exactly what I was looking for
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Martin Vanyavchich suggestion would be better approach for its simplicity and clean .

<edit>I dont like to depend finally block for an logic/control flow. I use finally only for deallocating a resource</edit>
 
Hebert Coelho
Ranch Hand
Posts: 754
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed. He gave a better solution.

The code I wrote, you just adapted his code, so he could see where he was missing! [=
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I presume the break; statement was only there to see whether we are awake?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic