aspose file tools*
The moose likes Beginning Java and the fly likes Check if my int contains an int (try/catch) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Check if my int contains an int (try/catch) " Watch "Check if my int contains an int (try/catch) " New topic
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: 11422
    
  16

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)


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
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: 19722
    
  20

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11422
    
  16

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: 39436
    
  28
Not convinced. You want what Rob said:Or something similar.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19722
    
  20

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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Check if my int contains an int (try/catch)