//将字符串转换为整型
//思路:特殊的输入测试:
//1,考虑字符串是否为空。2.字符串问空的时候的返回0,和真实的返回0直键的区别。3,字符串中出现0~9的字符处理
//4.字符串中出现*,¥等一下奇怪的符号时候的情况。
//功能测试:
//正数,负数和零
//边界测试:最大的正数,最小的负数。
public class StrToInt {
public boolean g_InVaild=
false;
public int strToInt(String s){
boolean minus=
false;
int result=0
;
int i=0
;
int len=
s.length();
if(s==
null)
return 0
;
if(s.length()==0
)
return 0
;
//int n=Integer.parseInt(s);//如果不让调用ParseInt.那么怎么写。
char firstChar=s.charAt(0
);
if(firstChar<'0'
){
if(firstChar=='-'
){
minus=
true;
}
else if(firstChar!='+'
)
throw new NumberFormatException();
if(len==1
)
throw new NumberFormatException();
i++
;
}
while(i<
len){
if(s.charAt(i)>='0'&&s.charAt(i)<='9'
){
int flag=minus?-1:1
;
result=result*10+flag*(s.charAt(i)-'0'
);
if(minus&&result>Integer.MAX_VALUE||!minus&&result<
Integer.MIN_VALUE){
result=0
;
break;
}
i++
;
}
else{
result=0
;
break;
}
}
if(i==
len){
g_InVaild=
true;
}
return result;
}
public static void main(String[] args)
{
String s="123"
;
StrToInt strInt=
new StrToInt();
int n=
strInt.strToInt(s);
System.out.println(n);
}
}
转载于:https://www.cnblogs.com/hupp/p/4775308.html