你好我是java的新手,我想问一些关于JOptionPane.showinput的问题,这样它只会接受字母/数字,如果输入的不正确,会导致错误,需要再次重新输入(在网站上搜索了一些解决方案,但他们不能处理我的代码,我不知道为什么) 最后我计划在我的joptionpane上进行多项选择,但是当我输入图标时,它被注册为错误 继承我的代码
JFrame frame = new JFrame("Student Record");
JOptionPane.showMessageDialog(frame,
"Welcome to the School's Student Grade Record!");
System.out.println("School's Student Grade Record");
String name;
name = JOptionPane.showInputDialog(frame,"Enter the name of the student");
System.out.println("The name of the student is: "+name);
Object[] choices = {"Filipino", "Math", "English"};
String grade = (String)JOptionPane.showInputDialog(frame,
"What grade subject do you choose to input?\"","Customized Dialog",
JOptionPane.PLAIN_MESSAGE,icon,choices,"Math");
System.exit(0);
答案 0 :(得分:1)
获取仅包含字母和数字的有效字符串,然后正则表达式是一个很好的帮助 ^ [a-zA-Z0-9] * $ 它只允许字母和数字以及以下代码会反复询问,直到给出有效的输入
String input;
String string = "";
do {
input = JOptionPane.showInputDialog("Enter String ");
if (input.matches("^[a-zA-Z0-9]*$")) {
string = input;
System.out.println("Name "+string);
} else {
System.out.println("Please enter a valid name containing: ‘a-z’ or ‘A-Z’ lower or upper case or numbers");
}
} while (!input.matches("^[a-zA-Z0-9]*$"));
现在关于您的图标是一种指定icons
的方法