JDK中字符串转成int值

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,考虑的不够全面
	     * 
	     * */
	
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值