aspose file tools*
The moose likes Beginning Java and the fly likes String to Integer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String to Integer" Watch "String to Integer" New topic
Author

String to Integer

Jamie Wool
Ranch Hand

Joined: May 03, 2004
Posts: 49
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

Joined: Apr 29, 2004
Posts: 75
Hi,
you can handle the occurence of non-numerical data with the NumberFormatException:

cu
Stefan
Jamie Wool
Ranch Hand

Joined: May 03, 2004
Posts: 49
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

Joined: Mar 26, 2004
Posts: 83
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
 
subject: String to Integer