This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Read input from user until an input is valid Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Read input from user until an input is valid" Watch "Read input from user until an input is valid" New topic
Author

Read input from user until an input is valid

Nelson Sam
Ranch Hand

Joined: Jun 12, 2010
Posts: 30
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

Joined: Sep 16, 2008
Posts: 241
You should try to put you number-getting logic in a loop, that would exit when you are satisfied with the users input.


SCJP 6, OCMJD 6, OCPJWSD 6
I no good English.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

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())!


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Hebert Coelho
Ranch Hand

Joined: Jul 14, 2010
Posts: 754

I believe this might help you! [=



C ya!


[uaiHebert.com] [Full WebApplication JSF EJB JPA JAAS with source code to download] One Table Per SubClass [Web/JSF]
Nelson Sam
Ranch Hand

Joined: Jun 12, 2010
Posts: 30
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

Joined: Jan 28, 2008
Posts: 5575

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

Joined: Jul 14, 2010
Posts: 754

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

Joined: Oct 13, 2005
Posts: 39045
    
  23
I presume the break; statement was only there to see whether we are awake?
 
GeeCON Prague 2014
 
subject: Read input from user until an input is valid