Reputation: 15
I'm having a problem parsing String to long. The string in question is a number that's preceded with spaces. For example: " 35".
NetBeans threw this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: " 35"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:578)
at java.lang.Long.parseLong(Long.java:631)
at Sis1.main(Sis1.java:75)
/Users/michaeladrian39/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
I want to parse the String "35" without the spaces to long. How to fix this error?
Upvotes: 0
Views: 3148
Reputation: 1604
Long.parseLong(String s, int radix) documentation states that the string 's' should not contain a non-digi character, Here's the excerpt from javadoc.
An exception of type NumberFormatException is thrown if any of the following situations occurs:
The first argument is null or is a string of length zero.
The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002d') or plus sign '+' ('\u002B') provided that the string is longer than
length 1.The value represented by the string is not a value of type long.
Examples:
parseLong("0", 10) returns 0L
parseLong("473", 10) returns 473L
parseLong("+42", 10) returns 42L
parseLong("-0", 10) returns 0L
parseLong("-FF", 16) returns -255L
parseLong("1100110", 2) returns 102L
parseLong("99", 8) throws a NumberFormatException
parseLong("Hazelnut", 10) throws a NumberFormatException
parseLong("Hazelnut", 36) returns 1356099454469L
String.trim() should work for you (as AlexR mentioned).
Upvotes: 0
Reputation: 761
String as = "6767";
long vb = Long.valueOf(as).longValue();
System.out.println(vb);
hope my code helps. Happy coding
Upvotes: 0
Reputation: 115378
You want to parse string "35" but try to parse string " 35" that has extra space. Remove it by calling (for example) trim()
:
Integer.parseInt(str.trim())
Upvotes: 3
Reputation: 45329
The problem is the space before 35. Remove the spaces and all should work.
Upvotes: 0