【java】【函数使用】Integer.parseInt异常处理

函数说明

Integer.parseInt(String s):方法用于将字符串参数作为有符号的十进制整数进行解析。
如果方法有两个参数, 使用第二个参数指定的基数,将字符串参数解析为有符号的整数。

  • parseInt(String s): 返回用十进制参数表示的整数值。
  • parseInt(String s, int radix):使用指定基数的字符串参数表示的整数 (基数可以是 10, 2, 8, 或 16 等进制数)
其他相关函数:

Integer.valueof(String s):把字符串s解析成Integer对象类型,返回的integer 可以调用对象中的方法。
StringUtils.defaultIfBlank(T str, T defaultStr):如果字符串为空白符就返回默认字符串defaultStr。可以以string的类型比较数值大小

Integer.parseInt(s)与Integer.valueOf(s)的区别

Integer.parseInt(s) 多次解析同一个字符串得到的int基本类型数据是相等的,可以直接通过“==" 进行判断是是否相等。基本类型不含equals方法。

 Integer.parseInt(s) == Integer.parseInt(s)

Integer.valueOf(s) 多次解析相同的一个字符串时,得到的是Integer类型的对象,得到的对象有时是同一个对象,有时是不同的对象,要根据把s字符串解析的整数值的大小进行决定:

  • 如果s字符串对应的整数值在 -128~127之间,则解析出的Integer类型的对象是同一个对象;
  • 如果s字符串对应的整数值不在-128~127之间,则解析出的Integer类型的对象不是同一个对象。
    不管对象是否相等,对象中的value值是相等的。
 Integer.parseInt(s) == Integer.parseInt(s)
 Integer.parseInt(s).equals(Integer.parseInt(s))

equals是比较的两个对象value值是否相等;
“==”是比较两个对象是否相等。

JDK源码中,由于在-128~127之间的整数值用的比较频繁,当每次要创建一个value值在-128~127之间的Integer对象时,直接从缓存中拿到这个对象,所以value值相同的Integer对象都是对应缓存中同一个对象。-128~127之外的整数值用的不是太频繁,每次创建value值相同的Integer对象时,都是重新创建一个对象,所以创建的对象不是同一个对象。

如下4种情况会抛 NumberFormatException 异常

  1. 第一个字符串参数s为null、或长度为0的字符串
  2. 第二个基数参数radix小于MIN_RADIX=2、或大于MAX_RADIX=36
  3. 字符串s的任何数字都不是指定基数的字符(数字/字母),除如下2种情况:
  • 第一个字符可以为减号-
  • 加号+且长度大于1第一个字符可以为减号-、或加号+且长度大于1
  1. 字符串s的值不是int型

常见的 NumberFormatException 异常

  • s为空串、空,如:parseInt("")
  • s中包括空格,如:parseInt("23 ")
  • 10进制时,s中包括字符串,如:parseInt(“a32”)
  • s不以-、+、数字开头、或包含字符串
  • s超出int允许的范围[-2147483648,2147483647],对应到2进制数字:"-10000000000000000000000000000000" (32位数字)~ “1111111111111111111111111111111”(31位数字)
  • 其他转换基数radix时,超出表示范围

源码

常见用法

 parseInt("0", 10) returns 0
 parseInt("473", 10) returns 473
 parseInt("+42", 10) returns 42
 parseInt("-0", 10) returns 0
 parseInt("-FF", 16) returns -255
 parseInt("1100110", 2) returns 102
 parseInt("2147483647", 10) returns 2147483647
 parseInt("-2147483648", 10) returns -2147483648
 parseInt("2147483648", 10) throws a NumberFormatException
 parseInt("99", 8) throws a NumberFormatException
 parseInt("Kona", 10) throws a NumberFormatException
 parseInt("Kona", 27) returns 411787

源码说明

    /**
     * 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 {@code '-'}
     * ({@code '\u005Cu002D'}) to indicate a negative value or an
     * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) to
     * indicate a positive value. The resulting integer value is
     * returned, exactly as if the argument and the radix 10 were
     * given as arguments to the {@link #parseInt(java.lang.String,
     * int)} method.
     *
     * @param s    a {@code String} containing the {@code int}
     *             representation to be parsed
     * @return     the integer value represented by the argument in decimal.
     * @exception  NumberFormatException  if the string does not contain a
     *               parsable integer.
     */
    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

 /**
     * Parses the string argument as a signed integer in the radix
     * specified by the second argument. The characters in the string
     * must all be digits of the specified radix (as determined by
     * whether {@link java.lang.Character#digit(char, int)} returns a
     * nonnegative value), except that the first character may be an
     * ASCII minus sign {@code '-'} ({@code '\u005Cu002D'}) to
     * indicate a negative value or an ASCII plus sign {@code '+'}
     * ({@code '\u005Cu002B'}) to indicate a positive value. The
     * resulting integer value is returned.
     *
     * <p>An exception of type {@code NumberFormatException} is
     * thrown if any of the following situations occurs:
     * <ul>
     * <li>The first argument is {@code null} or is a string of
     * length zero.
     *
     * <li>The radix is either smaller than
     * {@link java.lang.Character#MIN_RADIX} or
     * larger than {@link java.lang.Character#MAX_RADIX}.
     *
     * <li>Any character of the string is not a digit of the specified
     * radix, except that the first character may be a minus sign
     * {@code '-'} ({@code '\u005Cu002D'}) or plus sign
     * {@code '+'} ({@code '\u005Cu002B'}) provided that the
     * string is longer than length 1.
     *
     * <li>The value represented by the string is not a value of type
     * {@code int}.
     * </ul>
     * @param      s   the {@code String} containing the integer
     *                  representation to be parsed
     * @param      radix   the radix to be used while parsing {@code s}.
     * @return     the integer represented by the string argument in the
     *             specified radix.
     * @exception  NumberFormatException if the {@code String}
     *             does not contain a parsable {@code int}.
     */
    public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */

        if (s == null) {
            throw new NumberFormatException("null");
        }

        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        int result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }

参考:https://blog.csdn.net/u010502101/article/details/79162587

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值