java 字符串转化整型问题


public class StringParesInteger {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(Integer.MIN_VALUE);
		System.out.println(Integer.MAX_VALUE/10);
		System.out.println(pareseInt("="));
	}
	/**本题考查的主要是边界条件
	 * 1.穿入的字符串是否为空
	 * 2.字符串的首位是否为(+、-)
	 * 3.字符中是否有非法字符
	 * 4.穿入的字符串是否超过了整数的最大值(Integer.MAX_VALUE(2147483647)/Integer.MIN_VALUE(-2147483648))
	 * 
	 * @param data
	 * @return
	 */
	public static int pareseInt(String data){
		/*
		 * 判读穿传入的字符串是否为空
		 */
		if(data==null||data.length()==0){
			throw new NullPointerException("data is null");
		}
		int index=0;
		
		/**
		 * 
		 */
		//是否为负数
		boolean isPositive=true;
		// 临界值
		int limit = 0;
		//取出字符串的第一位
		char first=data.charAt(0);
		//第一位是负数的情况下
		if(first=='-'){
			isPositive=false;
			index++;
			//设置整形最小的负数(-2147483648)
			limit=-Integer.MIN_VALUE;
		}
		//第一位是整数的情况下
		if(first=='+'){
			isPositive=true;
			//设置最大的正数是(2147483647)
			limit=Integer.MAX_VALUE;
			index++;
		}
		//设置比较的边界值(214748364)
		int maxLimit=Integer.MAX_VALUE/10;
		int length=data.length();
		int result=0;
			while(index<length){
			char ch=data.charAt(index);
			//字符在0-9之间
			if(ch>'0'&&ch<'9'){
				//先判断原来的值是否大于比较的临界值
				if(result>maxLimit){
					throw new RuntimeException("整数越界了");
				}
				// 判断当前位的值+ch的值是否》整数的最大值
				if(result*10>limit-(ch-'0')){
					System.out.println("result-->"+(result*10));
					System.out.println("max----->"+(Integer.MAX_VALUE));
					System.out.println("result-->"+(Integer.MAX_VALUE-(ch-'0'))+" ch="+(ch-'0'));
					throw new RuntimeException("数组越界了s ");
				}
				index++;
				result=result*10+(ch-'0');
			}else{
				throw new RuntimeException("不是整数 ");
			}
		}
		//三目运算符
			
		return isPositive?result:-result;
	}
	
	

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值