Java 如何將String轉化為Int


在 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();
}

在轉換過程中需要注意,因為字符串中可能會出現非數字的情況,所以在轉換的時候需要捕捉處理異常


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM