-2

I am new to Java and I have been searching for 2 days how to accomplish this and still have not figured it out. In my if statement I need to ensure that if a user just presses enter with out entering a value a message will prompt for re entry, also if the user enters a value less than 1. Below is a snip of my code. I have read the int cant except null, and I have tried Integer , BUT my code wont run with that

int numberOfCars = -1
while (numberOfCars == null || numberOfCars < 1)
{
    numberOfCars = (JOptionPane.showInputDialog("Enter number of cars."));
    if(numberOfCars == null || numberOfCars < 1)
    {
        JOptionPane.showMessageDialog(null, "Please enter a value.");
    }
}
Jet813
  • 39
  • 8

2 Answers2

1
int numberOfCars = -1;
do {
     String answer = JOptionPane.showInputDialog("Enter number of cars.");
     if (answer != null && answer.matches("-?[0-9]+")) {
        numberOfCars = Integer.parseInt(answer);
        if (numberOfCars < 1) {
            JOptionPane.showMessageDialog(null, "Value must be larger than 1.");
        }
     } else {
        JOptionPane.showMessageDialog(null, "Value not a number.");
     }
} while (numberOfCars < 1);

This does a validation (matches) as otherwise parseInt would throw a NumberFormatException.

Regular expression String.matches(String)

.matches("-?[0-9]+")

This matches the pattern:

  • -? = a minus, optionally (?)
  • [0-9]+ = a character from [ ... ], where 0-9 is range, the digits, and that one or more times (+)

See also Pattern for info on regex.

Integer.parseInt(string)

Gives an int value taken from the string. Like division by zero this can raise an error, a NumberFormatException.

Here a do-while loop would fit (it rarely does). A normal while loop would be fine too.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • It would be more helpful to the OP if you explained `Integer.parseInt()` and `matches()` along with the applied regex because he/she is a beginner. Or provide a link to a reputable resource – eshirima Oct 05 '17 at 17:22
1

the JOptionPane.showInputDialog() will return you a String. You can use a try-catch statement to check wether the input value is correct when you try to parse it to int using Integer.parseInt(). This will work for all of your cases.

So this could work:

int numberOfCars = -1;

while(numberOfCars < 1){
  try{
    numberOfCars = JOptionPane.showInputDialog("Enter number of cars.");

    if(numberOfCars < 1){
      JOptionPane.showMessageDialog(null, "Please enter a value.");
    }

  }catch(NumberFormatException e){
      JOptionPane.showMessageDialog(null, "Please enter numeric value.");
  }
}