【发布时间】:2012-03-24 01:34:47
【问题描述】:
好的,我有这段代码要求输入用户名和密码。我用JOptionPane。我想要的程序是如果用户名字段上的输入有一个数字,则显示一条错误消息,然后返回上一个对话框再次询问用户名。我有这个 while 循环,但它没有按应有的方式运行。请帮忙。该程序不会在我的catch 方法上显示错误消息,也不会循环显示对话框。
public class SwingExercise {
public static void main(String[] args) {
String name = "";
String pw = "";
boolean input = true;
boolean hasDigit = false;
while (input) {
try {
while (name.equals("")) {
name = JOptionPane.showInputDialog(null, "Enter username:");
if (name.equals("")) {
JOptionPane.showMessageDialog(
null, "No input.", "Error", JOptionPane.ERROR_MESSAGE);
name = "";
}
while (hasDigit) {
for (int i = 0; i < name.length(); i++) {
if (Character.isDigit(name.charAt(i))) {
throw new InputMismatchException();
}
}
hasDigit = false;
}
}
input = false;
while (pw.equals("")) {
pw = JOptionPane.showInputDialog(null, "Enter password:");
if (pw.equals("")) {
JOptionPane.showMessageDialog(
null, "No input.", "Error", JOptionPane.ERROR_MESSAGE);
pw = "";
}
}
} catch (NullPointerException e) {
System.exit(0);
} catch (InputMismatchException e) {
JOptionPane.showMessageDialog(
null, "Invalid input.", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}
}
请务必提及有关我代码中其他行的任何 cmets,以及是否有任何不必要的行。提前谢谢你:)
【问题讨论】:
-
我已根据样式格式化了您的代码,因此更易于阅读。 (除了空格没有变化。)
标签: java while-loop try-catch joptionpane