| Author |
Check if my int contains an int (try/catch)
|
Peter Hammar
Ranch Hand
Joined: Mar 01, 2010
Posts: 34
|
|
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
Joined: Oct 02, 2003
Posts: 9955
|
|
|
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)
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Peter Hammar
Ranch Hand
Joined: Mar 01, 2010
Posts: 34
|
|
|
Ok, my bad, if I type in a "f" for example, instead of an int, the program crashes.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9955
|
|
|
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
Joined: Feb 09, 2010
Posts: 21
|
|
Try following...
convert input to Integer, If it is not int value then it will directly go in catch block...
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32708
|
|
|
Not convinced. You want what Rob said:Or something similar.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
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.
|
 |
 |
|
|
subject: Check if my int contains an int (try/catch)
|
|
|