4 回答

汪汪一只貓
TA貢獻(xiàn)1898條經(jīng)驗 獲得超8個贊
String myString = "1234";int foo = Integer.parseInt(myString);
如果你查看Java文檔,你會注意到“catch”是這個函數(shù)可以拋出一個NumberFormatException
,當(dāng)然你必須處理:
int foo;try { foo = Integer.parseInt(myString);}catch (NumberFormatException e){ foo = 0;}
(此處理默認(rèn)為格式錯誤的數(shù)字0
,但如果您愿意,可以執(zhí)行其他操作。)
或者,您可以使用Ints
Guava庫中的方法,該方法與Java 8結(jié)合使用Optional
,可以將字符串轉(zhuǎn)換為int的強(qiáng)大而簡潔的方法:
import com.google.common.primitives.Ints;int foo = Optional.ofNullable(myString) .map(Ints::tryParse) .orElse(0)

UYOU
TA貢獻(xiàn)1878條經(jīng)驗 獲得超4個贊
例如,有兩種方法:
Integer x = Integer.valueOf(str);// orint y = Integer.parseInt(str);
這些方法之間略有不同:
valueOf
返回一個新的或緩存的實例java.lang.Integer
parseInt
返回原語int
。
所有情況都是如此:Short.valueOf
/ parseShort
,Long.valueOf
/ parseLong
等。

斯蒂芬大帝
TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊
好吧,需要考慮的一個非常重要的一點(diǎn)是,Integer解析器會拋出Javadoc中所述的NumberFormatException 。
int foo;String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exceptionString StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exceptiontry { 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.}
嘗試從拆分參數(shù)中獲取整數(shù)值或動態(tài)解析某些內(nèi)容時,處理此異常非常重要。
添加回答
舉報
0/150
提交
取消