• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Check if a string is a number  RSS feed

 
Greenhorn
Posts: 9
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.


 
Sheriff
Posts: 5111
138
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.
 
Saloon Keeper
Posts: 4735
52
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: 9
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great, thank you for your help guys !
 
Marshal
Posts: 60062
188
  • 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.
 
Sheriff
Posts: 23689
50
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: 4735
52
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!