簡體   English   中英

我將如何濃縮這些方法?

[英]How would I condense these methods?

我無法弄清楚如何使用單個isValidPassword方法解決此問題,因此我將其分解為3個並使其正常工作。 有人可以向我解釋如何使用我編寫的代碼,如果可能的話可以壓縮它?

創建一個程序Password(密碼),提示用戶輸入密碼並確定密碼有效還是無效。 應該有一個靜態方法isValidPassword來驗證密碼(字符串)並返回true或false。 用戶只有3次嘗試輸入有效的密碼。 有效的密碼遵循以下三個規則:

- Must have at least eight characters.
- Must contain ONLY letters and digits.
- Must contain at least two digits.

使用程序對話框。 您必須為此程序使用String和Character類。 您不能使用正則表達式。 該程序只需要運行一次。

import javax.swing.JOptionPane;

public class Password {

    public static void main(String[] args) {

        int retryCount = 0;

        while (retryCount < 3) {

            retryCount++;

            String password = JOptionPane.showInputDialog("Please Enter the Password");
            if (CheckPassword(password)) {
                JOptionPane.showMessageDialog(null, "Congrats! Correct Password!");
                break;
            }
            else {

                JOptionPane.showMessageDialog(null, "Sorry, Invalid Password, you tried " + retryCount + " times");

                continue;
            }
        }
    }

    public static boolean CheckPassword(String password) {

        if (password.length() >= 8 & CheckAlphanumeric(password) && Check2digits(password)) {
            return true;
        }
        else {
            return false;
        }

    }

    public static boolean CheckAlphanumeric(String string) {

        for (int i = 0; i < string.length(); i++) {
            char x = string.charAt(i);
            if (x < 0x30 || (x >= 0x3a && x <= 0x40) || (x > 0x5a && x <= 0x60) || x > 0x7a) {
                return false;
            }
        }
        return true;
    }

    public static boolean Check2digits(String string) {

        int count = 0;
        for (int i = 0; i < string.length(); i++) {

            char c = string.charAt(i);
            if (Character.isDigit(c)) {
                count++;
            }

            if (count > 2) {
                return true;
            }

        }
        return false;
    }
}

讓我們快速回顧一下代碼:

  • 了解有關Java命名約定的信息。 方法名golCase ; 例如,返回布爾值的東西應該命名為isPasswordValid()
  • 您在這里所做的實際上是一種好方法:人們應該寧願使用許多小型方法(帶有良好的有意義的名稱!),而不要使用幾種大型方法(所謂的“抽象層”原理)
  • 您可以閱讀正則表達式以進行大多數檢查。 特別是檢查“僅ascii字符”是一個不錯的選擇! 因此,即使您的作業說“不要使用它們”; 可能想學習如何使用它們。 只為您自己的學習進度! 但是正如Kayaman指出的那樣, Character類具有許多用於此類檢查的靜態幫助器方法。 因此無需手動實現所有這些功能。
  • 您的代碼“邏輯上不一致”。 您的代碼是否在驗證某些字符串是否符合某些密碼規則(最小長度,最小位數)。 但是您的消息暗示此代碼正在檢查提供的密碼是否正確 如:輸入用戶的密碼,然后代碼檢查該密碼是否已知並與先前存儲的密碼匹配。 從這個意義上講:確保消息和代碼內容一致!

除此之外; 有關如何針對“真實世界”用法增強設計的建議。 事實是:可以有許多不同的規則來使密碼有效 這可能會隨着時間而改變。 通常,您可能想告訴用戶其輸入與哪個規則沖突。 解決這些問題的一種選擇:

public interface PasswordValidator {
  public void checkPassword(String password) throws InvalidPasswordException;
}

然后您創建各種實現,例如

public class MinimumLengthValidator implements PasswordValidator {
  @Override
  public void checkPassword(String password) throws   InvalidPasswordException {
    if (password.lenght() < 8) {
      throw new InvalidPasswordException("Given password is not long enough; expecting at least 8 characters");
    }
  }

然后,創建這些不同的驗證器類的實例。 並將它們存儲在某個數組中。 您對數組進行迭代,並單獨調用每個驗證。 當它失敗時,您會直接收到一個異常,並向用戶顯示一條好消息。

如前所述:上面的內容僅供參考(只需鍵入以下內容,請注意輸入錯誤)。

請看下面的代碼,它可以滿足您的所有要求-

這是純Java類。 您可以從以下代碼檢查邏輯。

程序edit1-指定密碼錯誤的原因。

public class Demo {

    private final int passwordAttempts = 3;
    private int countAttempts = 0;
    private String password;
    private int digitCounter = 0;

    public Demo() {
        init();
    }

    public static void main(String[] args) {
        new Demo();
    }

    private String checkPassword(String pass) {
        if (pass.length() >= 8) {
            if (StringUtils.isAlphanumeric(pass)) {
                char[] toCharArray = pass.toCharArray();
                for (int i = 0; i < toCharArray.length; i++) {
                    char check = toCharArray[i];
                    if(Character.isDigit(check)){
                        digitCounter++;
                    }
                }
                if (digitCounter >= 1) {
                    return "success";
                }else{
                    return "digit";
                }
            }else{
                return "alphanumeric";
            }
        }else{
            return "length";
        }
    }

    private void init() {
        while (countAttempts < passwordAttempts) {
           password = JOptionPane.showInputDialog("Please Enter the Password");
           digitCounter = 0;
           String passwordResult = checkPassword(password);
           if (passwordResult.equals("success")) {
              JOptionPane.showInputDialog("yes you entered correct password...");
           } else if(passwordResult.equals("length")){
              JOptionPane.showInputDialog("password must contain atleast 8 characters...");
           }else if(passwordResult.equals("alphanumeric")){
              JOptionPane.showInputDialog("only alphanumeric password accept...");
           }else if(passwordResult.equals("digit")){
              JOptionPane.showInputDialog("password must contain atleast two digits...");
           }
          countAttempts++;
        }
    }
}

現在只需要用其他僅指定消息的方法替換JOptionPane.showInputDialog()方法,因為showInputDialog()方法會提示輸入文本字段也輸入值,我們不希望這樣做。 我對揮桿一無所知。

根據您的評論-

此方法返回字符串值,例如成功,長度,字母數字,數字等。 下面我們將這個值與if if if上面的所有值進行比較。 每當它相等時,這意味着我們必須相應地顯示長度消息,字母數字字符串消息,數字消息。

依賴-

我正在使用Maven。 以下依賴項需要添加到pom.xml文件中。

<dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.0</version>
</dependency>

如果您不了解maven,則只需從此處下載jar文件,並在項目的lib文件夾中提供即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM