my dog learned polymorphism
The moose likes Beginning Java and the fly likes Input Validation Help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Input Validation Help" Watch "Input Validation Help" New topic

Input Validation Help

Peter Kolozvary

Joined: Sep 06, 2008
Posts: 6
I'm having a problem asking the user to validate their entry if they enter something other than a number.

I know I'm close.
Here is what I came up with so far...

Here is the full code:
marc weber

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Peter Kolozvary:
...salaries = keyboard.nextInt();

Scanner's nextInt() method will throw an exception if the next token cannot be parsed as an int, so you will need to validate before calling that.

Hint: Check Scanner's other methods in the API to see if there's a method that will check to see if the next token is an int.

Also, how much validation do you want/need to do here? For example, what if the user enters a dollar sign? Or misplaced commas? Or a decimal point? Or extra spaces? In those cases, you might be better off reading the input as a String, and then removing any character that is not a digit. (For that approach, see the Character class.)
[ October 21, 2008: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Muhammad Saifuddin
Ranch Hand

Joined: Dec 06, 2005
Posts: 1323

as Character class has isLetter and isDigit methods.
[ October 21, 2008: Message edited by: Muhammad Saifuddin ]

[Blog][Linkedin] How To Ask Questions On JavaRanch My OpenSource
I agree. Here's the link:
subject: Input Validation Help
It's not a secret anymore!