Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Check if my int contains an int (try/catch)

 
Peter Hammar
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

Im struggeling a little with a try/catch thing. I want to check so that my int x contains an int (if its something else the program crashes). The x should only contain numbers, otherwise the user should be promted to type in a number.



Is there a way to check this?

Regards
Hristo
 
fred rosenberger
lowercase baba
Bartender
Posts: 12198
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if it is an int, what else COULD it contain? (Note: There is a big difference between an int, an Integer, and a String that may contain something that can be parsed into an integer value)
 
Peter Hammar
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, my bad, if I type in a "f" for example, instead of an int, the program crashes.
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the hasNextXXX methods of Scanner. They tell you if the next token is an int / byte / ... Don't forget to consume that token or you will loop forever.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12198
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can also try using the Integer class' parseInt() method. It takes a String and attempts to convert it to an Integer for you, but it can throw an exception.
 
Nehel Patel
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try following...
convert input to Integer, If it is not int value then it will directly go in catch block...

 
Campbell Ritchie
Sheriff
Pie
Posts: 50240
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not convinced. You want what Rob said:Or something similar.
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And note that call on line 4 - it takes away the non-int token so hasNextInt() will evaluate the next token. It's return value is ignored since you don't need it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic