• Post Reply Bookmark Topic Watch Topic
  • New Topic

Check if a string is a number  RSS feed

 
Day Vide
Greenhorn
Posts: 8
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone,

I have a question. In my program I have some code to change a string to a integer but I keep getting errors in my program everytime the user enters a string without numbers or a string with numbers like this :
" 123" or "abc123".

How can I check if the string is numeric before converting it to an integer ?
Here is my code :



Thank you.


 
Knute Snortum
Sheriff
Posts: 4287
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could set an int variable to capture the output of parseInt() and surround that with a try/catch block, or you could put all of that into a method, boolean isStringNumeric(String), that returns true if the try block succeeds and false if it fails.
 
Carey Brown
Saloon Keeper
Posts: 3328
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You could place the try/catch stuff inside a helper method but you'd have to decide what is an appropriate thing to return. In some cases returning -1 would work. You could also return an Integer object or null if it fails. Or you could return an OptionalInt object.
 
Day Vide
Greenhorn
Posts: 8
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great, thank you for your help guys !
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aternative: use a Scanner.Beware: A String like "123 CodeRanch" will count has having a next int.
 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also beware: all of the code discussed so far will accept "-42" as a number, although that isn't a valid value for a coin (in most countries).
 
Carey Brown
Saloon Keeper
Posts: 3328
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's some samples of helper methods.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!