Search code examples
javaexceptionprimitive

Java Exception Handling to Check Primitive Types


I have a GUI program that simulates a fuel station.

In the program, there are 3 input fields:

  • itemName
  • number of Units(or volume in L)
  • and amount in pence (per unit or litre).

You can then chose to add the item by volume, or by units. The idea is that you can buy fuel and other items (such as food), with minimal input boxes.

I'm using exception handling to check the input is what I want it to be:

  • An int value to add by units
  • and a double value to add by volume.

My code so far recognises that a double has been entered where it wants an integer, and throws the error.

For example, the input of: item Name: Chocolate, Amount(or Litres): 2.5, Price: 85 gives the error: 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)");
    }

However when adding by volume, I can't get the program to only accept double values, or anything that uses a decimal point. An int can be passed in and accepted as a double value, which I don't want. The code I'm using is very similar:

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)");
    }

If anyone could point me in the right direction of any way of solving this, that would be great.

Thank you


Solution

  • Try this. It checks if the number contains a . char which would make it a double

    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)");
    }
    

    EDIT: combined with codeboxs answer a solution would be

    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)");
    }