2016-09-07 30 views
1

如果參數是0到255(包括0和255)之間的整數的字符串表示形式,則需要我的代碼返回true,否則返回false。parseInt vs isDigit

例如: 字符串「0」,「1」,「2」......「254」,「255」是有效的。

填充字符串(例如「00000000153」)也是有效的。

isDigit顯然也會工作,但我想知道這是否會更有益,和/或這將甚至與填充字符串一起工作?

public static boolean isValidElement(String token) { 
    int foo = Integer.parseInt("token"); 
    if(foo >= 0 && foo <= 255) 
     return true; 
    else 
     return false; 
    } 
+0

您的代碼無效? – passion

+2

JavaScript和Java是兩種完全不同的語言。 –

回答

2

isDigit是行不通的,因爲它需要一個字符作爲輸入,如果是從0到9的一個數字返回true [編號:isDigit javadoc]

因爲你的情況,你需要測試所有數字的字符串表示從0到255,因此您必須使用parseInt

此外還檢查傳遞的令牌是否爲有效數字,通過捕獲NumberFormatException並返回false以防它不是有效整數。

public static boolean isValidElement(String token) { 
    try{ 
     int foo = Integer.parseInt(token); 
     if(foo >= 0 && foo <= 255) 
      return true; 
     else 
      return false; 
    } catch (NumberFormatException ex) { 
     return false; 
    } 
} 
+0

「catch(NumberFormatException ex)」中的catch和ex是什麼意思?你爲什麼打開試試? –

+0

'try'和'catch'是Java關鍵字。如果提供的輸入不能被解析爲整數(例如'Integer.parseInt(「randomText」)''),'parseInt'將會拋出'NumberFormatException'。 'try-catch'是一種語法,用於捕獲該異常並執行正確的操作,即返回'false',因爲輸入不是有效的元素(不是0到255之間的數字表示)。你可以在[java官方教程](https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html)中閱讀更多關於try-catch的內容。 –

0

你可以使用正則表達式:

return token.matches("1?\\d{1,2}|2[0-4]\\d|25[0-5]"); 
0

那麼的Integer.parseInt將拋出NumberFormatException如果該字符串不是一個有效的數字,只是要記住。

我會使用commons-math3庫中的NumberUtils.isDigit()來檢查,然後使用Integer.valueOf這是一個有效的數字解析器。

if (NumberUtils.isDigit(token)) { 
    int foo = Integer.valueOf(token); 
    return (foo >=0 && foo <=255); 
} 
0

Integer.parseInt拋出一個NumberFormatException如果轉換是不可能的。考慮到這一點,你可以使用這段代碼片段。 不需要額外的依賴關係。

public static boolean isValidElement(String token) { 
    try { 
     int value = Integer.parseInt(token); 
     return value >= 0 && value <= 255; 
    } catch(NumberFormatException e) { 
     return false; 
    } 
}