Integer.parseint in Java, exception when '+' comes first

前端 未结 6 681
生来不讨喜
生来不讨喜 2020-12-19 03:31

Integer.parseInt(\"-1000\"); returns -1000 as the output.

Integer.parseInt(\"+500\"); throws an exception.

How will I be able to re

相关标签:
6条回答
  • 2020-12-19 04:01

    Try DecimalFormat like with the pattern "+#;-#". It will handle explicit signed parsing. Breakdown of the pattern:

    • The first part (before ;) is the positive pattern, it has to start with an + char
    • The second part is the negative and has to start with a - char

    Example:

    DecimalFormat df = new DecimalFormat("+#;-#");
    System.out.println(df.parse("+500"));
    System.out.println(df.parse("-500"));
    

    Outputs:

    500
    -500
    
    0 讨论(0)
  • 2020-12-19 04:06

    The implementation has changed from java 6 to 7. Intger.parseInt("+500") used to Exception till java 6 , but works perfectly fine with java 7

    0 讨论(0)
  • 2020-12-19 04:13

    One option is to use Java 7... assuming that behaves as documented:

    Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.

    It looks like this was a new feature introduced into Java 7 though. The JDK 6 docs only indicate that - is handled.

    0 讨论(0)
  • 2020-12-19 04:13

    The method is behaving as described in the documentation:

    The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value.

    You need to skip the first character if it is a + to do the parse correctly:

    if (s.charAt(0) == '+') s = s.substring(1);
    int val= Integer.parseInt(s);
    
    0 讨论(0)
  • 2020-12-19 04:20

    public static int parseInt(String s) throws NumberFormatException

    Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.

    Javadoc

    0 讨论(0)
  • 2020-12-19 04:24

    I am using Java 7, and Integer.parseInt("+500"); is not throwing any exception.

    The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.

    Java 7 documentation for Integer.parseInt(String)

    0 讨论(0)
提交回复
热议问题