Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Input Validation Help

 
Peter Kolozvary
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Muhammad Saifuddin
Ranch Hand
Posts: 1324
Android Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as Character class has isLetter and isDigit methods.
[ October 21, 2008: Message edited by: Muhammad Saifuddin ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic