0

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?

4 Answers 4

3

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())
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is the space before 35. Remove the spaces and all should work.

1 Comment

If your string is dynamic, then call string.trim() and then passit to Long.parseLong() -- as syggested by AlexR.
0
String as = "6767";
      long vb = Long.valueOf(as).longValue();
      System.out.println(vb);

hope my code helps. Happy coding

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.