因此,我必须编写一个提示用户输入密码的程序,该密码必须遵循三个要求:至少 8 个字符长,只有字母和数字,以及至少两位数字。现在,我创建的用于检查这三个要求的方法我认为是合理的,但是我的程序还必须进行一些异常处理,并且如果其中一个要求关闭,则能够要求用户重新输入密码并显示相应的错误消息遵循每个要求。我创建了一个字符串 errorMessage 来中继该消息,但是当我尝试在我的 main 中调用它时它给了我一个错误?
我的另一个问题是必须使用 JPasswordField 将密码输入我的程序,但我什至很难设置它,因为我阅读的 JPanel、按钮和动作事件等许多其他因素必须随之而来. 我尝试使用 JPasswordField 并注意到输入密码的行将其作为数组输入,当我的 checkPassword 方法需要一个字符串时,我怎样才能将该密码作为字符串输入?
到目前为止,这就是我的程序所拥有的:
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javafx.event.ActionEvent;
public class Ed10Chp6Ex6Point18CheckPasswordProgram {
public static void main(String[] args) {
final JFrame frame = new JFrame("Check Password Program");
JLabel jlbPassword = new JLabel("Please enter the password: ");
JPasswordField jpwName = new JPasswordField(15);
jpwName.setEchoChar('*');
jpwName.addActionListener(new ActionListener()) {
public void actionPerformed(ActionEvent e) {
JPasswordField input = (JPasswordField) e.getSource();
char[] password = input.getPassword();
if(checkPassword(password)){
JOptionPane.showMessageDialog(frame, "Congradulations, your password follows all the requirements");
}
else{
JOptionPane.showMessageDialog(frame, errorMessage);
}
}
}
}
public static boolean checkPassword(String x) {
String errorMessage = "";
//must have at least eight characters
if (x.length() < 8){
errorMessage = "The password you entered is invalid, password must be at least 8 characters";
return false;
}
//consists of only letters and digits
for (int i = 0; i < x.length(); i++) {
if (!Character.isLetter(x.charAt(i)) && !Character.isDigit(x.charAt(i))) {
errorMessage = "The password you entered is invalid, password must contain only letters and digits";
return false;
}
}
//must contain at least two digits
int count = 0;
for (int i = 0; i < x.length(); i++) {
if (Character.isDigit(x.charAt(i))){
count++;
}
}
if (count >= 2){
return true;
}
else {
errorMessage = "The password you entered is invalid, password must contain at least two digits";
return false;
}
}
}
如果我的一些问题看起来很初级,我提前道歉,任何帮助将不胜感激,谢谢!