您好,我是java新手,我想问一些有关 JOptionPane.showinput 的问题,以便它只接受字母/数字,如果输入不正确,则会导致错误并需要再次重新输入(在网站上搜索了一些解决方案,但它们不适用于我的代码,我不知道为什么) 最后,我计划在我的 joptionpane 上进行多种选择,但是当我输入 icon 时,它被注册为错误 这是我的代码
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);
最佳答案
要获取仅包含字母和数字的有效字符串,那么正则表达式是一个很大的帮助^[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 的方法
关于java - JOptionPane.showinputdialog 只输入字母或数字以及多项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40038600/