有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如果用户输入错误的数字数据,如何调用错误消息

do {
    number = (String)JOptionPane.showInputDialog(null,"Quantity : ","TRIAL",JOptionPane.QUESTION_MESSAGE);
    if(number.matches("\\d+")) {
        qty = Integer.parseInt(number);
    }
    //    JOptionPane.showMessageDialog(null,"Invalid input !\n\nMin = 1\nMax = 100","TRIAL",JOptionPane.ERROR_MESSAGE);
} while(qty < 1 || qty > 100);
JOptionPane.showMessageDialog(null,number);

如果我将错误消息放在if内部或外部,如果用户输入正确的数据,错误消息仍然会出现


共 (3) 个答案

  1. # 1 楼答案

    如果输入与正则表达式不匹配,则需要显示消息。因此:

    if(number.matches("\\d+")){
        qty = Integer.parseInt(number);
    }
    //    JOptionPane.showMessageDialog(null,"Invalid input !\n\nMin = 1\nMax = 100","TRIAL",JOptionPane.ERROR_MESSAGE);
    

    需要变成这样:

    if(number.matches("\\d+")){
        qty = Integer.parseInt(number);
    } else {
        JOptionPane.showMessageDialog(null,"Invalid input !\n\nMin = 1\nMax = 100","TRIAL",JOptionPane.ERROR_MESSAGE);
    }
    

    现在你的意思是,如果它匹配OK,那么你就读取qty的新值,但是如果它不匹配,那么你就显示消息

    您可能会考虑另一种选择,即避免使用正则表达式,但只需尝试parseInt()调用,然后捕获无法转换的NumberFormatException结果

    (如果可以解析数字,但给出的结果超出了1到100的有效范围,则还需要一些逻辑来显示错误。)

  2. # 2 楼答案

    您可以将条件检查移动到循环中,并将循环更改为无限:

    while (true) {
        number = (String)JOptionPane.showInputDialog(null,"Quantity : ","TRIAL",JOptionPane.QUESTION_MESSAGE);
        if(number.matches("[1-9]\\d*")){
            qty = Integer.parseInt(number);
    
            if (qty >= 1 && qty <= 100) {
                 break;
            }
        }
    
        JOptionPane.showMessageDialog(null, "Invalid input !\n\nMin = 1\nMax = 100", "TRIAL", JOptionPane.ERROR_MESSAGE);
    }
    
    JOptionPane.showMessageDialog(null,number);
    

    在这种情况下,有一个无限循环,只有当输入的值仅包含数字且其值在[1100]范围内时,该循环才会中断

  3. # 3 楼答案

    How do I call error message if user input wrong numeric data

    相反,我建议为他们提供一个控件,使选择一个数字变得容易。具体来说,是一个带有微调器编号模型的微调器。像这样:

    import javax.swing.*;
    
    public class PickANumber {
    
        public static void main(String[] args) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    SpinnerNumberModel spinnerModel = 
                            new SpinnerNumberModel(0, 0, 100, 1);
                    JSpinner spinner = new JSpinner(spinnerModel);
                    while (spinnerModel.getNumber().intValue()<1) {
                        JOptionPane.showMessageDialog(
                                null, 
                                spinner, 
                                "Pick a number between 1 & 100!", 
                                JOptionPane.QUESTION_MESSAGE);
                    }
                    System.out.println(
                            "Number: " + spinnerModel.getNumber().intValue());
                }
            };
            SwingUtilities.invokeLater(r);
        }
    }