Click to See Complete Forum and Search --> : convert string to int


ailing
October 13th, 1999, 09:58 PM
Hello

I'm facing the problem of converting string to int.
I need to read data from .csv file. After reading each line, i will split the line into meaningful data.
While spilting the line, i need to detect whether the data read is a char or int.
Base on some criteria, if data read is a char, then set the value to zero.
Does anyone have a solution to this?

Thanks
Ailing.L

dcturner
October 14th, 1999, 02:40 AM
Using JDK 1.2, you can call the static function Integer.parseInt(String), which returns an int. (not an Integer - note the difference). Similar functions exist for doubles and floats.

If you are using an earlier version of Java, then you have to create a new Integer object, and call the intValue() function on it:
String s="12345";
int i = new Integer(s).intValue()


All of this is documented at
http://java.sun.com/products/jdk/1.2/docs/api/index.html. The Number objects are in the package java.lang.

Dave Turner

ailing
October 14th, 1999, 04:34 AM
hi! Thanks for ur response.

You were saying that i could use Interger.parseInt(String s) method to get what i want.
I tried out ur suggestion but it works if the string contains numbers (String s = "12345").
What if i wanted to convert (String s= "check") to an integer (zero) - is this possible?
Any suggestion?

Regards
Ailing.L

dcturner
October 14th, 1999, 04:41 AM
Integer.parseInt(String) throws a NumberFormatException if the string is not convertible. You could do something like:
int answer;
try
{
answer = Integer.parseInt(s);
}
catch (NumberFormatException numFormEx)
{
answer = 0;
}

ailing
October 14th, 1999, 05:06 AM
YAP! i got it running. Thanks alot.