2017-08-03 168 views
0

我需要解析一個字符串用戶id到我使用的整數Integer.parseInt(String s)但它返回null/nil,如果那裏字符串有/保存非十進制/整數值,在這種情況下,我需要指定默認整數值爲0我怎樣才能解析字符串爲int與默認值?

我試過了,但它(? 0)似乎不工作,我不知道它是否是正確的語法。

String userid = "user001"; 
int int_userid = Integer.parseInt(userid) ? 0; 

如果賦值爲空,如何將默認值賦值爲整數?

字符串用戶ID是作爲Web服務函數調用的一部分的參數參數,所以我無法將其數據類型更新爲整數。

+4

您已經發明瞭Java中不存在的語法。如果parseInt不能解析字符串,則會拋出異常。你可以抓住例外來處理這種情況。 – khelwood

+2

「,但它返回空,如果有字符串有非整數值」不,它不。一個int返回方法不能返回null。它引發一個異常。 – Michael

+0

當您運行該程序時,您應該會在eclipse控制檯中看到一個異常。 – deepakl

回答

1

您可以使用正則表達式嘗試此方法。

public static int parseWithDefault(String s, int default) { 
    return s.matches("-?\\d+") ? Integer.parseInt(s) : default; 
} 
8

這句法不會爲Integer.parseInt()工作,因爲它會導致NumberFormatException

你可以處理它這樣

String userid = "user001"; 
int int_userid; 
try 
{ 
    int_userid = Integer.parseInt(userid); 
} 
catch(NumberFormatException p_ex) 
{ 
    int_userid = 0; 
} 
+0

你從哪裏發明了'p_ex'? – xenteros

+1

只需要一個變量名就可以在這裏發現 – Lars

+0

這只是NumberFormatException的一個變量。你可以使用它像'p_ex.printStackTrace()' – Yannick

-2
int int_userid; 
try { 
    int_userid = Integer.parseInt(userid); // try to parse the given user id 
} catch (Exception e) { // catch if any exception 
    int_userid = 0; // if exception assign a default value 
} 
+2

看,這是答案之一,但唯一一個甚至沒有一個詞來解釋... – xenteros

+0

但這不應該是投票的理由,反正我會記住這一點。 – deepakl

+1

[解釋解答](// meta.stackexchange.com/q/114762)對未來的訪問者更有用,並且更有可能獲得投票。評論票不計入名譽,所以他們經常被用來表示同意。如果您覺得評論「太嘮叨」並且應該被刪除,您可以隨時將其標記爲主持人注意。 – whrrgarbl

0
String userid = "user001"; 
int int_userid = Integer.parseInt(userid) != null ? Integer.parseInt(userid) : 0); 

你的意思是這樣的語法? 但由於一個int永遠不能null你,而不是做:

String userid = "user001"; 
int int_userid; 
try { 
    int_userid= Integer.parseInt(userid); 
} catch (NumberFormatexception e) { 
    int_userid = 0; 
} 
5

您可以用這種方式與String::matches這樣的:

String userid = "user001"; 
int int_userid = userid.matches("\\d+") ? Integer.parseInt(userid) : 0; 

也CA使用-?\d+的正面和負面的價值觀:

int int_userid = userid.matches("-?\\d+") ? Integer.parseInt(userid) : 0; 
+3

是不是我downvote,我不是一個正則表達式大師,但它似乎是一個迂迴的方式,不會失敗的負數? – PeterJ

+0

@PeterJ現在呢? :) –

+2

@YCF_L完美的過度工程:D – xenteros

2

我相信你可以通過下面的m來實現你想要的ethod:

public static int parseIntWithDefault(String s, int default) { 
    try { 
     return Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
     return default; 
    } 
} 

現在只分配:

int int_userid = parseIntWithDefault(userId, 0); 

請有記住,使用Java應該使用有關格式化代碼的Java的良好做法。 int_userid絕對是要改進的地方。

1

你最有可能使用apache.commons.lang3不已:

NumberUtils.toInt(str, 0); 
1

這可能是有點過度工程,但你可以用番石榴的Ints.tryParse(String)與Java 8的選配是這樣的:

int userId = Optional.ofNullable(Ints.tryParse("userid001")).orElse(0) 
相關問題