如何创建一个不接受输入对话框中输入的特定数量数字的异常?
How to create an exception that doesn't accept certain amount of numbers entered in input dialog?
Pattern p = Pattern.compile("^[0-9]{0,3}$");
Matcher m = p.matcher(in);
if (m.find()) {
JOptionPane.showMessageDialog(null, " 4 integers please");
}
是加号的按钮
尝试创建限制对话框中数字数量的异常,它会检测数字是否在限制范围内但不会停止程序。
我不知道这段代码的上下文,但它没有调用自定义异常。如果用户输入无效输入,只需使用循环显示对话框:
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
的 class
class:
public class MyException extends Exception {
public MyException(int amount) {
super("Only " + amount + " integers are allowed");
}
}
并在您的 if 语句中实现它:
if (!m.find()) {
throw new MyException(4);
}
您提供的代码确实少于需要的代码..
但这里有一种方法可以在 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);
}
});
您可以简单地使用 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.");
}
}
}
Pattern p = Pattern.compile("^[0-9]{0,3}$");
Matcher m = p.matcher(in);
if (m.find()) {
JOptionPane.showMessageDialog(null, " 4 integers please");
}
是加号的按钮
尝试创建限制对话框中数字数量的异常,它会检测数字是否在限制范围内但不会停止程序。
我不知道这段代码的上下文,但它没有调用自定义异常。如果用户输入无效输入,只需使用循环显示对话框:
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
的 class
class:
public class MyException extends Exception {
public MyException(int amount) {
super("Only " + amount + " integers are allowed");
}
}
并在您的 if 语句中实现它:
if (!m.find()) {
throw new MyException(4);
}
您提供的代码确实少于需要的代码..
但这里有一种方法可以在 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);
}
});
您可以简单地使用 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.");
}
}
}