简体   繁体   中英

giving a null value to a int type variable

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM