Java認證基礎知識:java字串轉化整型問題
java 字串轉化整型問題
public class StringParesInteger {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
tln(_VALUE);
tln(_VALUE/10);
tln(pareseInt("="));
}
/**本題考查的主要是邊界條件
* 1.穿入的字串是否為空
* 2.字串的首位是否為(+、-)
* 3.字元中是否有非法字元
* 4.穿入的字串是否超過了整數的最大值(_VALUE(2147483647)/_VALUE(-2147483648))
*
* @param data
* @return
*/
public static int pareseInt(String data){
/*
* 判讀穿傳入的字串是否為空
*/
if(data==null||th()==0){
throw new NullPointerException("data is null");
}
int index=0;
/**
*
*/
//是否為負數
boolean isPositive=true;
// 臨界值
int limit = 0;
//取出字串的第一位
char first=At(0);
//第一位是負數的情況下
if(first=='-'){
isPositive=false;
index++;
//設定整形最小的負數(-2147483648)
limit=_VALUE;
}
//第一位是整數的情況下
if(first=='+'){
isPositive=true;
//設定最大的正數是(2147483647)
limit=_VALUE;
index++;
}
//設定比較的`邊界值(214748364)
int maxLimit=_VALUE/10;
int length=th();
int result=0;
while(index'0'&&ch<'9'){
//先判斷原來的值是否大於比較的臨界值
if(result>maxLimit){
throw new RuntimeException("整數越界了");
}
// 判斷當前位的值+ch的值是否》整數的最大值
if(result*10>limit-(ch-'0')){
tln("result-->"+(result*10));
tln("max----->"+(_VALUE));
tln("result-->"+(_VALUE-(ch-'0'))+" ch="+(ch-'0'));
throw new RuntimeException("陣列越界了s ");
}
index++;
result=result*10+(ch-'0');
}else{
throw new RuntimeException("不是整數 ");
}
}
//三目運算符
return isPositive?result:-result;
}
}