This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String to Integer

 
Jamie Wool
Ranch Hand
Posts: 49
  • 0
  • 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
 
Stefan Krompass
Ranch Hand
Posts: 75
  • 0
  • 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
  • 0
  • 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);

}
 
Ben Buchli
Ranch Hand
Posts: 83
  • 0
  • 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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic