2014-10-27 41 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();