這個方法是將字符串轉換為整型
一、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、判斷是否為負值 返回結果
