我正在制作一个JOptionpane,用户必须输入姓名。所以它不能为空,也不能是数字
空白部分正在运行,但现在我必须找到数字部分的解决方案
正如你在我的代码中看到的那样,我做了一个while循环来检查“naam”是否为空。现在我需要找到一种方法来检查“naam”是不是一个数字。
String naam = JOptionPane.showInputDialog("Geef uw naam in: ");
while (naam.equals("")) {
JOptionPane.showMessageDialog(null, "Geef een naam in", "Geef naam", JOptionPane.ERROR_MESSAGE);
naam = JOptionPane.showInputDialog("Geef uw naam in: ");
答案 0 :(得分:3)
您可以直接在对话框中过滤输入,而不是弄乱必须显示错误对话框并重新显示对话框......
import java.awt.EventQueue;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class TestOptionPane08 {
public static void main(String[] args) {
new TestOptionPane08();
}
public TestOptionPane08() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField name = new JTextField(10);
((AbstractDocument) name.getDocument()).setDocumentFilter(new DocumentFilter() {
public String filter(String text) {
StringBuilder sb = new StringBuilder(text.length());
for (char c : text.toCharArray()) {
if (!Character.isDigit(c)) {
sb.append(c);
}
}
return sb.toString();
}
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, filter(string), attr);
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String filter = filter(text);
super.replace(fb, offset, length, filter, attrs);
}
});
JOptionPane.showMessageDialog(null, name, "Name Please", JOptionPane.QUESTION_MESSAGE);
}
});
}
}
现在,您可以将JTextField
添加到JPanel
并添加JLabel
甚至错误消息......
答案 1 :(得分:1)
if (naam.matches("\\d+")) {/*it is a number*/}
如果字符串与作为参数给出的正则表达式匹配,则 String.matches(regexp)
返回true
。在此示例中,\\d+
匹配一个或多个数字。
您可以尝试其他模式以禁止包含无效字符的字符串(例如“My#name
”),但这取决于您对“名字字符”的定义。
例如[A-Z][a-z]*(?:\\s[A-Z][a-z]*)
匹配带有一个或多个大写字符序列的字符串,后跟零或多个小写字符,每个序列用单个空格分隔,例如My Name Is X
。
答案 2 :(得分:1)
您可以使用正则表达式检查它是否包含任何数字。 java中的正则表达式“\\ D”表示非数字,“+”表示1或更多。因此,您可以将while循环更改为:
while (!naam.matches("\\D+"))
这将包括空等号检查,因为您需要至少有一个非数字才能匹配。