• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to check if the user input is a string of an int  RSS feed

 
Aron Silvester
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to get an int input from the user. I want to validate the input but I don't know how to check if the input is a word, like "Hi" (in which case the program will crash), or a number (something I want for user input). Is there a method int he API that checks this? Below is my code if you'd care to see it. If you see, the conditional statement for if is blank. This is where I check if it's a string or a number. Any ideas how i can accomplish this??

 
Fred Kleinschmidt
Bartender
Posts: 571
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just useand then see if Integer.parseInt(value) is successful
 
Paweł Baczyński
Bartender
Posts: 2082
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or use keys.hasNextInt().
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although you may want to lead with hasNext() to determine if there was user-input at all.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you use hasNextInt() as Paweł said. No need for next or hasNext.
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My bad, I thought hasNextInt() returned immediately in the absence of user input. I'm not sure why. Probably a lack of coffee.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct. If you don't give hasNextInt enough coffee, it will sulk and sit there waiting for input. The documentation says that
The API documentation wrote:The scanner does not advance past any input.
… and in the introduction of the same page it says
A scanning operation may block waiting for input.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!