2013-02-19 42 views
2

我正在尋找一些有關我的功課的幫助。我希望用戶輸入一個數字字符串,然後將其轉換爲整數。但是我想製作一個循環來檢測用戶是否輸入了錯誤的值,例如「One Hundred」與「100」相對應。Java:檢測變量是一個字符串還是一個整數

我在想什麼是應該做這樣的事情:

do{ 
     numStr = JOptionPane.showInputDialog("Please enter a year in numarical form:" 
         + "\n(Ex. 1995):"); 
     num = Integer.parseInt(numStr); 
      if(num!=Integer){ 
      tryagainstr=JOptionPane.showInputDialog("Entered value is not acceptable." 
            + "\nPress 1 to try again or Press 2 to exit."); 
    tryagain=Integer.parseInt(tryagainstr); 
      } 
      else{ 
      *Rest of the code...* 
      } 
      }while (tryagain==1); 

但我不知道如何定義「整數」的價值。我基本上想讓它看看它是否是一個數字,或者如果用戶輸入錯誤的東西來防止它崩潰。

+1

'嘗試'的東西。 – 2013-02-19 16:05:20

+2

['Integer.parseInt'](http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29)方法拋出'NumberFormatException'如果輸入不能作爲整數解析。你只需要使用'try/catch'。 – 2013-02-19 16:07:21

回答

1

試試這個

int num; 
String s = JOptionPane.showInputDialog("Enter a number please"); 
while(true) 
{ 
    if(s==null) 
     break; // if you press cancel it will exit 
    try { 
     num=Integer.parseInt(s); 
     break; 
    } catch(NumberFormatException ex) 
    { 
     s = JOptionPane.showInputDialog("Not a number , Try Again"); 
    } 
} 
+0

謝謝!我現在更好地理解try/catch。我運行了類似於這個的地方,我告訴它在變量等於1時執行{try/catch},並且每次進入catch時變量都保持1以保持循環。謝謝! – Dave555 2013-02-20 15:29:03

5

試試這個:

try{ 
     Integer.valueOf(str); 
    } catch (NumberFormatException e) { 
     //not an integer 
    } 
1

使用正則表達式驗證字符串的格式,並在其上只接受數值:

Pattern.matches("/^\d+$/", numStr) 

matches方法將返回true如果numString包含有效的數字序列,但當然輸入可以高於Integer的容量。在這種情況下,您可以考慮切換到longBigInteger類型。

1

嘗試使用instanceof,如果你想整間只檢查這種方法將幫助您檢查多種類型

之間例

if (s instanceof String){ 
// s is String 
}else if(s instanceof Integer){ 
// s is Integer value 
} 

和字符串,你可以使用@NKukhar代碼

try{ 
     Integer.valueOf(str); 
    } catch (NumberFormatException e) { 
     //not an integer 
    } 
相關問題