• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

NumberFormatException Error

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
}
}
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank a lot! it fixes the problem.
Elizabeth
 
He repaced his skull with glass. So you can see his brain. Kinda like this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic