public class A16 {
/**
* 输入一个表示整数的字符串,把该字符串转换成整数并输出。
* 输入字符串"345",则输出整数345。
* 数值小的时候,还好说,要考虑比较大的数
*
* 首先是JDK提供的功能,学习之
* @param args
*/
public static void main(String[] args) {
String test = "255653";
//
int dd = parseInt(test);
System.out.println(dd);
}
//首先考虑的是进制的问题,默认的情况下是十进制
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
public static int parseInt(String s, int radix)
throws NumberFormatException
{
//不相信传进来的参数
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, max = s.length();
int limit;
int multmin;
int digit;
if (max > 0) {
//判断正负数(一般的情况下,是比较容易遗忘的)
if (s.charAt(0) == '-') {
negative = true;
limit = Integer.MIN_VALUE;
i++;
} else {
limit = -Integer.MAX_VALUE;
}
multmin = limit / radix;
if (i < max) {
//既然考虑了进制的问题,那么在字符串中每一个字符转成数字的时候,应该有对应的数值
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw new NumberFormatException(s);
} else {
//为什么把这个结果变成了负数
result = -digit;
}
}
while (i < max) {
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw new NumberFormatException(s);
}
if (result < multmin) {
throw new NumberFormatException(s);
}
result *= radix;
//这个现实也比较的有意思
if (result < limit + digit) {
throw new NumberFormatException(s);
}
//因为这个时候是负值,故使用减号
result -= digit;
}
} else {
throw new NumberFormatException(s);
}
if (negative) {
if (i > 1) {
return result;
} else { /* Only got "-" */
throw new NumberFormatException(s);
}
} else {
return -result;
}
}
/**
* 看到JDK的代码后,才感觉自己的代码,写的是漏斗百出
* 怨不得,自己的代码上线后,要一直的该bug,考虑的不够全面
*
* */
}
JDK中字符串转成int值
最新推荐文章于 2021-11-04 15:25:22 发布