Java Exception Handling to Check Primitive Types -


I have a GUI program that limits fuel stations.

In the program, 3 input fields:

  • Item name
  • Number of units (or volume in L)
  • More pence Amount (per unit or liter) in

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

I am using exception handling to check input, which I want to do:

  • and a double value by quantity to append.
  • My code still accepts that a double has been entered where it wants integer, and throws an error. For example, item name: chocolate, amount (or liter): 2.5, value: 85 returns error: used code looks like this

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

    While adding to the volume, I can not find the program to accept only double values, or anything that uses a decimal point It can be passed to a int and it is accepted as a double value, which I do not want. The code I am using is very similar:

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

    If someone can tell me in the correct direction of this sort of solution, then it would be good.

    Thank you

    Try it, checks that the number is one in char which it Double make

      try {if (! NumOfUnitsField.getText (.) Contains (".")) {New number format exception ("not double"); } Double item volume = double. PRSDB (NumOfUnitsField.getText ()); } Hold (NumberFormatException exception) {SetErrorField ("Input appropriate type (actual number for volume, integer for units)" should be); }  

    Edit: A solution will be answered with codeboxes

      try {Pattern p = Pattern.compile ("\\ d + \" \. \\ d + "); If (! P.matcher (NumOfUnitsField.getText ()). Matches ()) {new number format exception ("not double"); } Double item volume = double. PRSDB (NumOfUnitsField.getText ()); } Hold (NumberFormatException exception) {SetErrorField ("Input appropriate type (actual number for volume, integer for units)" should be); }  

    Comments