publicstaticintparseInt(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,或者传入的进制不满足要求,直接抛出异常 //支持的进制范围是 2~36
if (s == null) { thrownew NumberFormatException("null"); }
if (radix < Character.MIN_RADIX) { thrownew NumberFormatException("radix " + radix + " less than Character.MIN_RADIX"); }
if (radix > Character.MAX_RADIX) { thrownew 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; } elseif (firstChar != '+') throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-" throw NumberFormatException.forInputString(s); i++; } //根据最大值,以及进制数,计算出 //如果为正数,limit为-Integer.MAX_VALUE //如果为负数,limit为Integer.MIN_VALUE,也就是说limit一直为负值 multmin = limit / radix; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE digit = Character.digit(s.charAt(i++),radix); //获取到数字的值,如果小于0则抛出异常,如果小于 if (digit < 0) { throw NumberFormatException.forInputString(s); } //因为result一直为正值,如果小于multmin说明有异常 if (result < multmin) { throw NumberFormatException.forInputString(s); } //进位 result *= radix; //如果result<limit+digit 也就是result-digit < limit,说明越界了 if (result < limit + digit) { throw NumberFormatException.forInputString(s); } //倒着计算值 result -= digit; } } else { throw NumberFormatException.forInputString(s); } //如果为符号为负,直接返回,否则取反,因为result是倒着计算的,取反之后为正数 return negative ? result : -result; }