• Post Reply Bookmark Topic Watch Topic
  • New Topic

scanner input validation

 
Henry Schneider
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm a learn by doing type, so I decided to create a simple program to multiply two inputs using java.util.Scanner . Deciding I need to validate my input to make sure I multiply numerics is a challenge for a novice like me. Originally, I thought I could use nextDouble and simply verify that whatever I accept is in fact a double (didn't work because if I put a nonnumeric in a double, bad things happen). However, now I am thinking I should bring in my input as a string then convert the string to a double. If you could provide some insight as to how I might validate my inputs so that I have numerics before I multiply my two inputs, I'd be thankful.
Kind regards
 
Norm Radder
Bartender
Posts: 1526
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java has many conversion routines that will do the conversion for you. Most of them will throw an exception if the data is bad. Look at how to use the try{}catch() block.
Put the code that throws the exception inside the try-catch block and catch the exception that will thrown for invalid data. Then in the catch block you can put your code to handle the problem.

For example say Integer.toInt() throws a BadIntException.

 
Henry Schneider
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!