This week's book giveaway is in the Python forum.
We're giving away four copies of Python Continuous Integration and Delivery and have Moritz Lenz on-line!
See this thread for details.
Win a copy of Python Continuous Integration and Delivery this week in the Python forum!
  • 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:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
Bartenders:
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

String to Integer  RSS feed

 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys,
I need to work out the best way of handling the below conversion of a string to an int, the example works fine but occassionally the string i'm converting contains non numerical charachter and i naturally get an exception error. Basically i really need to carry the conversion but want to know how best to deal with the odd occurance of non numerical chars without the program crashing, is there an effective way of dealing with this???
if(strTerm.equals("price")){
Price=Integer.parseInt(strEntry);

Cheers

Jamie
 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
you can handle the occurence of non-numerical data with the NumberFormatException:

cu
Stefan
 
Jamie Wool
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That catches that exception thank, but how do i get the int out now.
It currently sets it to -1
I thought the maybe i could use subString to locate the invalid string and chop out the int, but what happens if there are charachters before and after.
Cheers

Jamie
if(strTerm.equals("price")){
try {Price = Integer.parseInt(strEntry);}
catch (NumberFormatException nfe)
{ // Whatever you do with non-numeric data.
System.out.println("&&&&&&&Caught the non numerical data"+nfe);

}
 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use a do-while loop for as long as the int to be parsed is not a valid int.
something like this will do:

notice though, you might be throwing an IOException with the BufferedReader.
[ May 11, 2004: Message edited by: Ben Buchli ]
 
She still doesn't approve of my superhero lifestyle. Or this shameless plug:
Become a Java guru with IntelliJ IDEA
https://www.jetbrains.com/idea/
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!