1

したがって、ユーザーにパスワードの入力を促すプログラムを作成する必要があります。このパスワードは、8 文字以上、文字と数字のみ、および 2 桁以上の 3 つの要件を満たす必要があります。これらの 3 つの要件を確認するために作成したメソッドは適切だと思いますが、私のプログラムではいくつかの例外処理も行う必要があり、要件の 1 つがオフになっている場合はユーザーにパスワードの再入力を求め、それぞれのエラー メッセージを表示する必要があります。それぞれの要件に沿ってください。そのメッセージを中継する文字列 errorMessage を作成しましたが、メインで呼び出そうとするとエラーが発生しますか?

私のもう1つの問題は、JPasswordFieldを使用してパスワードをプログラムに取り込む必要があることですが、JPanel、ボタン、読んだアクションイベントなどの他の多くの要因がそれに付随する必要があるため、パスワードの設定にも苦労しています. JPasswordField を使用しようとしましたが、パスワードを取得する行が配列として取得することに気付きました。

これまでのところ、私のプログラムには次のものがあります。

   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;
    }
}
}

私の質問のいくつかが初歩的であると思われる場合は、事前にお詫び申し上げます。

4

2 に答える 2