2014-03-25 15 views
1

所以我正在做一個應用程序,用戶輸入一個輸入,當他點擊按鈕它執行一個命令,但輸入必須是一個整數,所以我添加了一個檢查,但即使當我輸入一個整數是給我一個錯誤說「你只能輸入數字!」我如何在輸入中檢查是否有數字或不在擺動?

繼承人我的代碼:

 String itemId = textField1.getText(); 
     String itemAmount = textField2.getText(); 

     int id = Integer.parseInt(itemId); 
     int amount = Integer.parseInt(itemAmount); 

     if (!Double.isNaN(id) || !Double.isNaN(amount)){ 
      JOptionPane.showMessageDialog(
        null, "You can only enter numbers!" 
      ); 

即使我輸入數字的文本框我仍然無法通過這項測試,爲什麼和如何解決這一問題?謝謝。

+0

[限制JTextField中輸入整數(可能重複http://stackoverflow.com/questions/11093326/restricting-jtextfield -input-to-integers) – alex2410

+0

這個問題在這裏問了很多次,試着再次搜索之前再次搜索。 「 – alex2410

回答

1
Double.isNaN(id) 

返回true,如果指定的號碼是不是非數字(NAN)值, 否則爲假。

但是你id和你amout是整數,所以它會返回錯誤的,你做!Double.isNaN(id)和反轉布爾型,所以結果是正確的。它只是一個邏輯失敗。刪除!

if (Double.isNaN(id) || Double.isNaN(amount)){ 
    JOptionPane.showMessageDialog(null, "You can only enter numbers!"); 
} 

注:

int id = Integer.parseInt(itemId); 
int amount = Integer.parseInt(itemAmount); 

Sourround這兩條線有try和catch塊,否則你將得到一個NumberFormatException如果輸入不是數字。

try 
{ 
    int id = Integer.parseInt(itemId); 
    int amount = Integer.parseInt(itemAmount);+ 
}catch(NumberFormatException e) 
{ 
    //print your error here 
} 
+0

nvm,謝謝先生! – Boolena

+0

不客氣! – kai

5

但輸入必須是一個整數,所以我增加了一個檢查,但即使 當我輸入一個整數是給了我一個錯誤說:「你只能輸入數字 !」

有兩種方法,使用

  • JFormattedTextField上用數字格式,JSpinner的使用SpinnerNumberModel的

  • 添加的DocumentFilter到了JTextField

+3

*」帶'SpinnerNumberModel'的''JSpinner'「*幸福。 :)這最好的(海事組織)方法是要走的路。 –

+0

+1完全同意。如果人們努力通過這些組件('JSpinner'和'JFormattedTextField')爲我們提供輸入驗證問題的解決方案,爲什麼要重新發明輪子? – dic19

2

其實你可以做到這一點像這樣:

String itemId = textField1.getText(); 
String itemAmount = textField2.getText(); 
int id; 
int amount; 
try{ 
    id = Integer.parseInt(itemId); 
    amount = Integer.parseInt(itemAmount); 
} 
catch(NumberFormatException e){ 
     JOptionPane.showMessageDialog(null, "You can only enter numbers!"); 
} 

如果itemIDitemAmount值不是語法分析,是指非數字被輸入

+1

捕獲'NumberFormatException',而不是'Exception'。否則,如果其他事情被破壞,並且你得到一個'NullPointerException'或一個'ArrayIndexOutOfBoundsException',它仍然會說「你只能輸入數字!」當問題與輸入數字無關時。 – immibis

+1

沒關係。 'Exception'仍然會遇到'NumberFormatException'。但是好的,我會修改它(我不認爲'NullPointerException'或者'ArrayIndexOutOfBoundsException'可能發生在這兩行內部try try :)) – Baby

+1

@TAsk *「最簡單的一個!!」*方式不!您應該使用'SpinnerNumberModel'檢查'JSpinner'爲此,如[另一個答案](http://stackoverflow.com/a/22629861/418556)中所述。比試圖強制將一個方形釘(整數)插入圓孔(文本字段)要簡單得多。 :)對於[示例](http://stackoverflow.com/a/10021773/418556).. –

相關問題