This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes NumberFormatException Error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "NumberFormatException Error" Watch "NumberFormatException Error" New topic
Author

NumberFormatException Error

Elizabeth Chen
Greenhorn

Joined: Aug 09, 2001
Posts: 7
I always get the NumberFormatException error from the following simple program called TestSort.java. The error came from where I tried to convert a string into a Long object. Can anyone know what the problem is? Thanks.
TestSort.java:

import java.util.*;
public class TestSort implements Comparator {
public int compare (Object obj1, Object obj2) {
int i, j, k;
String str1 = (String) obj1;
String str2 = (String) obj2;
i = str1.lastIndexOf(' ');
j = str2.lastIndexOf (' ');
Long li = Long.valueOf(str1.substring (i));
Long lj = Long.valueOf(str2.substring (j));
k = li.compareTo(lj);
return k;
}

public static void main (String args[]) {
TreeSet ts = new TreeSet (new TestSort());
ts.add ("aaa 9000000000");
ts.add ("bbb 7000000000");
ts.add ("ccc 8000000000");
System.out.println ("ts contains " + ts);
}
}
Donny Wi
Greenhorn

Joined: Jan 24, 2002
Posts: 13
Your code:

When you call the substring, it will start from the space to the end of the string. If your string is "aaa 1000" the value of str1.substring (i) is " 1000". When you convert that string into Long, the valueOf method does not like the extra space in front of the number.
To solve this problem you can do the following:

or


Donny Widjaja
Elizabeth Chen
Greenhorn

Joined: Aug 09, 2001
Posts: 7
Thank a lot! it fixes the problem.
Elizabeth
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: NumberFormatException Error
 
Similar Threads
Array List
TreeSet's add() method runtime error
checking among a range of values
how comparator works
question concering hashCode(), equals() and operator ==