第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Java中將String轉(zhuǎn)換為int?

如何在Java中將String轉(zhuǎn)換為int?

陪伴而非守候 2019-05-24 15:51:33
如何在Java中將String轉(zhuǎn)換為int?我怎么能轉(zhuǎn)換String成intJava中?我的字符串只包含數(shù)字,我想返回它代表的數(shù)字。例如,給定字符串"1234",結(jié)果應(yīng)該是數(shù)字1234。
查看完整描述

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í)行其他操作。)

或者,您可以使用IntsGuava庫中的方法,該方法與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)


查看完整回答
反對 回復(fù) 2019-05-24
?
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.valueOfparseShort,Long.valueOfparseLong等。


查看完整回答
反對 回復(fù) 2019-05-24
?
斯蒂芬大帝

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)容時,處理此異常非常重要。


查看完整回答
反對 回復(fù) 2019-05-24
  • 4 回答
  • 0 關(guān)注
  • 838 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號