Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate integer field if user input nothing? [closed]

Tags:

java

swing

do{
         try{
            input = (String) JOptionPane.showInputDialog(null,"Food quantity","Dope Alley",JOptionPane.QUESTION_MESSAGE);
            quantity = Integer.parseInt(input);
            if(quantity <= 0 || quantity > 100){
                JOptionPane.showMessageDialog(null,"Invalid input . Number only .\n\nMininum order = 1\nMaximum order = 100","Dope Alley",JOptionPane.ERROR_MESSAGE);
            }
        }catch(NumberFormatException e){
            JOptionPane.showMessageDialog(null,"Invalid input . Number only .\n\nMininum order = 1\nMaximum order = 100","Dope Alley",JOptionPane.ERROR_MESSAGE);
        }
    }while(quantity <= 0 || quantity > 100);

catch(NumberFormatException e) how to clarify variable e in my code? in my code the program stated that variable e is not used . so how can i used it

like image 910
Zaem Shakkir Avatar asked Mar 06 '26 21:03

Zaem Shakkir


1 Answers

You could use a regular expression. \\d+ will match consecutive digits. Also, I'd suggest a do-while loop. Something like

int quantity = -1;
do {
    input = (String) JOptionPane.showInputDialog(null, "Food quantity",
            "Dope Alley", JOptionPane.QUESTION_MESSAGE);
    if (input.matches("\\d+")) {
        quantity = Integer.parseInt(input);
    }
} while(quantity < 1 || quantity > 100);
like image 193
Elliott Frisch Avatar answered Mar 09 '26 09:03

Elliott Frisch