gpt4 book ai didi

java - 不循环并显示错误消息

转载 作者:行者123 更新时间:2023-12-01 15:28:40 25 4
gpt4 key购买 nike

好的,我有这段代码,要求输入用户名和密码。我使用了 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);
}
}
}

请提及有关我的代码中其他行的任何注释以及是否有任何不必要的行。预先感谢您:)

最佳答案

似乎完全没有办法进入 while(has Digit) 循环,因为您将其设置为 false,并且没有任何设置将其设置为 true

关于java - 不循环并显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9848398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com