您的位置:首页 > 产品设计 > UI/UE

字符串数字转换成整型(不用Integer.valueOf()方法)

2011-06-26 00:49 791 查看
/**
* 把一个字符串数字转换成整型,禁止使用Integer.valueOf(i)方法
* @author alen
*
*/
public class ChangeStr {
public static int Convert(String str) throws Exception {
int a = 0,i = 0;

char[] cStr = str.toCharArray();

//判断是否是负数
if (cStr.length > 0 && cStr[0] == '-') {
i = 1;
}
for (; i < cStr.length; i++) {
if ('0' > cStr[i] || cStr[i] > '9') {
throw new NumberFormatException();
}
a = a * 10 + Character.digit(cStr[i], 10);
}
if (cStr.length > 0 && cStr[0] == '-') {
a = -a;
}
return a;
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Convert("23456");
}
}


原文地址:http://blog.csdn.net/alen1985/archive/2010/07/05/5713141.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: