源码浅谈(二):java中的 Integer.parseInt(String str)方法

这个方法是将字符串转换为整型

 

一、parseInt方法 ,可以看到默认又调用了parseInt(s,10) ,  第二个参数为基数,默认10 ,当然也可以自己设置 

    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

 

二、parseInt(String s, int radix)

 

 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.
         */
     // 第一步、判断字符串参数是否为null 
        if (s == null) {
            throw new NumberFormatException("null");
        }
     
     // 第二步,判断基数是否小于最小基数 为2
if (radix < Character.MIN_RADIX) { throw new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX"); }
     // 第三步,判断基数是否大于最大基数 为36
if (radix > Character.MAX_RADIX) { throw new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX"); } int result = 0;

     // 标识,是否为负数,默认false boolean negative
= false;
// 字符串转换为char数组后的 下标和数组长度
int i = 0, len = s.length(); int limit = -Integer.MAX_VALUE; int multmin; int digit;
// 第四步,判断字符串长度是不大于0
if (len > 0) {
        // 取第一个字符
char firstChar = s.charAt(0);
       // 字符ASCII是否小于'0' ,可能为 '+' '-' , 如果不是<'0' ,则为数组 ,略过该if{}
if (firstChar < '0') { // Possible leading "+" or "-" // 如果第一个字符是'-' ,说明是负数,则负数标识改为true ,限制改为最小标识
          if (firstChar == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (firstChar != '+')
            // 如果第一个字符不是'-' 也不是'+' ,异常
throw NumberFormatException.forInputString(s);           // 第一字符<'0' 且长度为1 则不是数字 异常 if (len == 1) // Cannot have lone "+" or "-" throw NumberFormatException.forInputString(s); i++; } multmin = limit / radix;
       // 遍历字符串转为的字符数组,将每一个字符转为10进制值,并拼接
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; }

 

 

综上,该方法源码的执行流程:

  

1、parseInt(String s)--内部调用parseInt(s,10)(默认为10进制)
2、判断字符串参数是否不为null,否则异常 
3、判断基数是否在最小基数和最大基数之间,否则异常
4、判断字符串长度是否>0 5、判断第一个字符是否是符号位,是的话判断+-符号,不是的话则第一位不是字符,直接下一步遍历每一个字符 6、循环遍历确定每个字符的十进制值 7、通过
*= 和-= 进行计算拼接 8、判断是否为负值 返回结果

 

转载于:https://www.cnblogs.com/xqxacm/p/9908989.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值