java 字符串转化整型问题

2014-11-24 03:26:38 · 作者: · 浏览: 0
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
  
'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; } }