2014-10-27 42 views
0

我有一個GUI程序,模擬加油站。Java異常處理來檢查原始類型

在節目中,有3個輸入字段:

  • ITEMNAME
  • 單位數(或體積在L)
  • 和量在便士(每單位或升)。

然後,您可以選擇按體積或按單位添加項目。這個想法是,你可以購買燃料和其他物品(如食物),最小的輸入框。

我使用異常處理檢查輸入是什麼,我希望它是:

  • int值由單位
  • double值體積添加補充。

我的代碼到目前爲止認識到一個double已經進入它想要一個整數,並引發錯誤。

例如,輸入:item Name: Chocolate, Amount(or Litres): 2.5, Price: 85給出了錯誤:The code used looks like this

if (e.getSource() == AddByNumOfUnits) { 
    try { 
     Integer.parseInt(NumOfUnitsField.getText()); 
    } catch (NumberFormatException exception) { 
     SetErrorField("Input must be the appropriate type (real number for volume, integer for units)"); 
    } 

但是體積增加的時候,我不能讓程序只接受double值,或任何使用小數點。一個int可以通過並接受爲double值,我不想要。我使用的代碼非常相似:

if (e.getSource() == AddByVolume) { 
    try { 
     double itemVolume = Double.parseDouble(NumOfUnitsField.getText()); 
    } catch (NumberFormatException exception) { 
     SetErrorField("Input must be the appropriate type (real number for volume, integer for units)"); 
    } 

如果任何人都可以在此解決任何方式指向正確的方向我,那將是巨大的。

謝謝

+3

爲什麼5不會被接受爲雙精度?你想讓用戶輸入5.0?爲什麼? – 2014-10-27 12:41:32

+0

基本上,當顯示數據回到用戶時,我使用數據類型來追加「公升......」。因此,當你說例如輸入「巧克力棒,數量:2,價格85」時,你仍然可以按體積添加,從而得到輸出「2升巧克力」 – Stinkidog 2014-10-27 12:50:36

+0

我沒有看到任何與此有關的事實,你強迫用戶輸入5.0而不是5.看起來你很煩惱用戶的一個不好的原因。 – 2014-10-27 12:54:07

回答

1

試試這個。它檢查數字是否包含a。焦炭這將使雙

try { 
    if(!NumOfUnitsField.getText().contains(".")){ 
     throw new NumberFormatException("Not a double"); 
    } 
    double itemVolume = Double.parseDouble(NumOfUnitsField.getText()); 
} catch (NumberFormatException exception) { 
    SetErrorField("Input must be the appropriate type (real number for volume, integer for units)"); 
} 

編輯:與codeboxs組合回答的解決辦法是

try { 
    Pattern p = Pattern.compile("\\d+\\.\\d+"); 
    if(!p.matcher(NumOfUnitsField.getText()).matches()){ 
     throw new NumberFormatException("Not a double"); 
    } 
    double itemVolume = Double.parseDouble(NumOfUnitsField.getText()); 
} catch (NumberFormatException exception) { 
    SetErrorField("Input must be the appropriate type (real number for volume, integer for units)"); 
} 
+0

如果我輸入'25.' – 2014-10-27 12:42:08

+0

那麼它會在下一行中仍然不能解析爲雙精度型 – cholewa1992 2014-10-27 12:42:47

+0

謝謝!這現在工作。看起來相當簡單的解決方案,我已經完全忽略了 – Stinkidog 2014-10-27 12:56:17

1

Double.parseDouble()會很樂意接受整數值,所以你應該嘗試一個正則表達式來代替。這將檢查您在小數點前後是否至少有一位數字:

Pattern p = Pattern.compile("\\d+\\.\\d+"); 
boolean isDecimalValue = p.matcher(NumOfUnitsField.getText()).matches();