如何创建一个不接受在输入对话框中输入的一定数量的数字的异常?

mdfafbf1  于 2021-07-08  发布在  Java
关注(0)|答案(3)|浏览(192)

这个问题在这里已经有答案了

一次捕获多个异常(28个答案)
上个月关门了。

Pattern p = Pattern.compile("^[0-9]{0,3}$");
Matcher m = p.matcher(in);
if (m.find()) {
    JOptionPane.showMessageDialog(null, " 4 integers please");
}

它是一个添加数字的按钮
尝试创建限制对话框中数字数量的异常,它会检测数字是否在限制范围内,但不会停止程序。

0g0grzrc

0g0grzrc1#

我不知道这段代码的上下文,但它不调用自定义异常。如果用户输入无效输入,只需使用循环来显示对话框:

Pattern p = Pattern.compile("^[0-9]{0,3}$");
Matcher m = p.matcher(in);
while (!m.find()) {
    in = JOptionPane.showInputDialog(null, "Please only enter four integers:");
    m = p.matcher(in);
}
// ...

还有,你想改变吗 if(m.find())if(!m.find()) 否则,“请只输入四个整数:”对话框将仅在用户输入正确的整数数时显示。
如果必须使用异常,只需创建一个扩展 Exception 班级:

public class MyException extends Exception {

    public MyException(int amount) {
        super("Only " + amount + " integers are allowed");
    }

}

并在if语句中实现:

if (!m.find()) {
    throw new MyException(4);
}
km0tfn4u

km0tfn4u2#

你可以简单地使用 in.matches("\\d{4}") 仅当此条件为 true .

import javax.swing.JOptionPane;

public class Main {
    public static void main(String[] args) {
        String in = JOptionPane.showInputDialog("Number: ");
        if (in.matches("\\d{4}")) {
            // ...Code to add the value to the textarea
        } else {
            JOptionPane.showMessageDialog(null, "Only 4 digits please.");
        }
    }
}
wlp8pajw

wlp8pajw3#

你提供的代码确实比需要的少。。
但是这里有一种方法,当你的 TextArea 超过3。
让我们说你的 TextArea 被命名为 txtArea .

txtArea.textProperty().addListener((observable, oldValue, newValue) -> {
        if(newValue.length()>3){
            JOptionPane.showMessageDialog(null, " 4 integers please");
            //Do whatever you need after the Alert is shown
            txtArea.setText(oldValue);
        }
    });

相关问题