当用户未输入时,如何验证整数字段?

3
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);

在我的代码中,程序指出变量e未被使用,如何澄清这个变量?当出现NumberFormatException异常时,可以使用catch(NumberFormatException e)来捕获该异常。如果您想要使用这个变量e,可以在catch块中添加相关代码以处理该异常。

1个回答

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);

1
也许使用 "\\d{1,8}" 可以防止智能引号溢出 :) - Bohemian
如果数量为-1,我认为如果用户输入0,它将继续进行。 - Zaem Shakkir
@ZaemShakkir 不是的,因为 0-1 都小于 1 - Elliott Frisch
1
你可以再保留一个计数器来记录循环运行的次数,如果不是第一次运行,则显示错误消息。 - Elliott Frisch
如果我使用try和catch,这是可能的吗? - Zaem Shakkir
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接