Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NumberFormatException Error

 
Elizabeth Chen
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Elizabeth Chen
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank a lot! it fixes the problem.
Elizabeth
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic