File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String to Integer" Watch "String to Integer" New topic

String to Integer

Jamie Wool
Ranch Hand

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


Stefan Krompass
Ranch Hand

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

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.

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 ]
jQuery in Action, 2nd edition
subject: String to Integer
Similar Threads
problem converting unicode characters from native to Java
to_number function question.
HowTo --> GroovyShell().evaluate("['item1', 'item2', 'item3']")
Error parsing special characters
EL's treatment of empty string