0
我试图编写一个程序,提示用户输入密码,然后根据密码是否为“有效”,在命令提示符处输出密码或告诉用户再次输入密码。用户有3次尝试,直到程序终止。在用户密码无效的情况下执行while循环
我的循环,应该运行,直到passString变量有效(由isPasswordValid方法确定)或用户有三次尝试。
问题是我的while循环从不执行,即使我将passString初始化为“无效”密码。 isPasswordValid在程序第一次运行时应该返回false,因此执行循环。
目前我的程序打印出“你的密码是:”,它没有打印密码,因为循环从不执行,因此从不提示用户输入密码。
import javax.swing.*;
import java.util.*;
public class Password {
public static void main(String[] args) {
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter a password:");
JPasswordField pass = new JPasswordField(10);
//place the label and the password field on the JPanel container
panel.add(label);
panel.add(pass);
String[] options = new String[]{"OK", "Cancel"};
int tries = 0;
String passString = "";
while (!isValidPassword(passString) && tries < 3) {
//I've tried isValidPassword(passString) == false
//and the loop still did not execute
int option = JOptionPane.showOptionDialog(null, panel, "The title",
JOptionPane.OK_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[1]);
char[] password = pass.getPassword();
StringBuilder glue = new StringBuilder();
for (int x = 0; x < password.length; x++) {
glue.append(password[x]);
passString = glue.toString();
}
tries++;
}
System.out.print("Your password is: " + passString);
}
public static boolean isValidPassword(String word) {
int intCounter = 0;
int letCounter = 0;
for (int x = 0; x < word.length(); x++) {
if (Character.isDigit(x)){
intCounter++;
}
if(Character.isLetter(x)) {
letCounter++;
}
if(!Character.isLetterOrDigit(x)) {
return false;
}
}
if (intCounter >= 2 && word.length() <= 8) {
return true;
}
return true;
}
}
我已添加: if(word.isEmpty()){ return false; } 我的方法。该程序现在成功提示用户输入密码。现在的问题是,即使我输入的密码符合“有效”密码所需的标准,程序也会不断询问用户,直到用完尝试并退出循环。 –
我不确定什么构成有效的密码。从阅读你的功能,我会说这是: – MattCash
必须是1到8个字符的长度,必须包括至少2位数字,不能包含特殊字符。它是否正确? @Jason_Silva – MattCash