It's not a secret anymore!
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "NumberFormatException Error" Watch "NumberFormatException Error" New topic

NumberFormatException Error

Elizabeth Chen

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

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

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:


Donny Widjaja
Elizabeth Chen

Joined: Aug 09, 2001
Posts: 7
Thank a lot! it fixes the problem.
I agree. Here's the link:
subject: NumberFormatException Error
jQuery in Action, 3rd edition