如果用户没有输入任何内容,如何验证整数字段?

时间:2015-10-25 04:02:27

标签: 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)如何在我的代码中澄清变量e?在我的代码中,程序声明不使用变量e。那我怎么用呢

1 个答案:

答案 0 :(得分:5)

您可以使用正则表达式。 \\d+将匹配连续数字。另外,我建议使用do-while循环。像

这样的东西
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);