糯米文學吧

位置:首頁 > IT認證 > JAVA認證

java字符串轉化整型問題

JAVA認證1.06W

2016年JAVA認證考試已經在緊張的備考中了,在後期會考來臨之際我們將會第一時間為廣大考生髮佈會考時間安排,請廣大考生隨時關注本站。下面是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;

}

}