这个方法是将字符串转换为整型
一、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、判断是否为负值 返回结果