有兩種方式java
Integer x = Integer.valueOf(str); // or int y = Integer.parseInt(str);
這兩種方式有一點點不一樣:this
valueOf
返回的是java.lang.Integer
的實例spa
parseInt
返回的是基本數據類型 intcode
Short.valueOf/parseShort
,Long.valueOf/parseLong
等也是有相似差異。orm
另外還需注意的是,在作int類型轉換時,可能會拋出NumberFormatException,所以要作好異常捕獲input
int foo; String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception try { foo = Integer.parseInt(StringThatCouldBeANumberOrNot); } catch (NumberFormatException e) { //Will Throw exception! //do something! anything to handle the exception. } try { foo = Integer.parseInt(StringThatCouldBeANumberOrNot2); } catch (NumberFormatException e) { //No problem this time but still it is good practice to care about exceptions. //Never trust user input :) //do something! anything to handle the exception. }