字符串转换成整数

/*
 * 输入一个表示整数的字符串,把该字符串转换成整数并输出,例如输入字符串"345",则输出整数345。
 * 
 * 需要考虑的问题:1.由于整数可能不仅仅之含有数字,还有可能以'+'或者'-'开头,表示整数的正负。2.处理非法输入。
 * 在使用指针之前判断这个指针是不是为空。3.输入的字符串中可能含有不是数字的字符。4.最后一个需要考虑的问题是溢出问题。
 */
public class atoiTest {
	public static long atoi(String str) throws Exception {
		boolean negative = false;
		long value = 0;
		if (str == null || str.equals("")) 
			throw new Exception("null string or the string has no character!");
		for (int i = 0; i < str.length(); i++) {
			if (i == 0 && (str.charAt(0) == '-' || str.charAt(0) == '+')) {
				if (str.charAt(0) == '-') {
					negative = true;				
				}
			} 
			else {
				if (str.charAt(i) >= '0' && '9' >= str.charAt(i)) {
					value = value * 10 + (str.charAt(i) - '0');
					if (value > Integer.MAX_VALUE) 
						throw new Exception("OUT OF INTEGER  RANGE");
				} 
				else 
					throw new NumberFormatException("not an integer");
			}
		}
		return negative == true ? value * -1 : value; 			
	}
	public static void main(String[] args) throws Exception {
		atoiTest at=new atoiTest();
		String[] str={"0", "-","01", "-1","123","289765","1000000000","-1000000000",
				"-1000000000000","+aa","-abc"};
		for(int i=0;i<str.length;i++){
			System.out.println("字符:"+str[i]);
			System.out.println("整数:"+at.atoi(str[i]));
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值