在 Java 中要將 String 類型轉化為 int 類型時,需要使用 Integer 類中的 parseInt() 方法或者 valueOf() 方法進行轉換.
String str = "123"; try { int a = Integer.parseInt(str); } catch (NumberFormatException e) { e.printStackTrace(); }
方法二
String str = "123"; try { int b = Integer.valueOf(str).intValue() } catch (NumberFormatException e) { e.printStackTrace(); }
在轉換過程中需要注意,因為字符串中可能會出現非數字的情況,所以在轉換的時候需要捕捉處理異常