在 Java 中要將 String 類型轉化爲 int 類型時,需要使用 Integer 類中的 parseInt() 方法或者 valueOf() 方法進行轉換.
例1:
1
2
3
4
5
6
|
String str = "123" ; try { int a = Integer.parseInt(str); } catch (NumberFormatException e) { e.printStackTrace(); } |
例2:
1
2
3
4
5
6
|
String str = "123" ; try { int b = Integer.valueOf(str).intValue() } catch (NumberFormatException e) { e.printStackTrace(); } |
在轉換過程中需要注意,因爲字符串中可能會出現非數字的情況,所以在轉換的時候需要捕捉處理異常
如果發現自己轉換的字符串都是數字,但還是拋異常,一般是存在空格之類的特殊字符,需要精確提取出字符串中的數字再進行轉換,例:'wt.oart.WTPart.343532329',提取字符串要提取從3到9,而不能直接從3開始到結束。
從字符串精確提取數字,參考:http://blog.csdn.net/realroman/article/details/76880223
一般採用正則表達式提取。
Ps:確定自己截取的字符串全是數字;
確定是小於或等於八位。