所以我必須編寫一個程序,提示用戶輸入一個密碼,該密碼必須符合三個要求:至少8個字符,只有字母和數字,至少有兩個數字。現在我創建的方法是檢查這三個要求,我相信它是正確的,但是我的程序還必須執行一些異常處理,並且如果其中一個要求關閉,可以要求用戶重新輸入密碼,並將相應的錯誤消息顯示爲遵循每個要求。我創建了一個字符串errorMessage來傳遞該消息,但是當我嘗試在我的主目錄中調用它時,它給了我一個錯誤?Java JPasswordField
我的另一個問題是密碼必須通過使用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;
}
}
}
我在先進的情況下,道歉我的一些問題顯得簡陋,任何幫助將不勝感激,謝謝!
你試過了嗎?String pass = new String(password);' –
哦哇,謝謝!把它放在char []密碼行後面,錯誤消失。你會碰巧知道爲什麼errorMessage的調用會出錯嗎? –
'errorMessage'未在'JOptionPane.showMessageDialog(frame,errorMessage)範圍內定義;' –