简体   繁体   English

我将如何浓缩这些方法?

[英]How would I condense these methods?

I couldn't figure out how to solve this problem using a single isValidPassword method so I broke it down into 3 and got it to work. 我无法弄清楚如何使用单个isValidPassword方法解决此问题,因此我将其分解为3个并使其正常工作。 Can someone explain to me how I could use the code I wrote and if possibly condense it? 有人可以向我解释如何使用我编写的代码,如果可能的话可以压缩它?

Create a program Password that prompts for a password from the user and determines if the password is valid or invalid. 创建一个程序Password(密码),提示用户输入密码并确定密码有效还是无效。 There should be a static method isValidPassword that validates the password (String) and returns either true or false. 应该有一个静态方法isValidPassword来验证密码(字符串)并返回true或false。 A user has ONLY three tries to enter a valid password. 用户只有3次尝试输入有效的密码。 A valid password follows these three rules: 有效的密码遵循以下三个规则:

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

Use dialog boxes for the program. 使用程序对话框。 You must use the String and Character classes for this program. 您必须为此程序使用String和Character类。 You may NOT use regular expressions. 您不能使用正则表达式。 The program only needs to run once. 该程序只需要运行一次。

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

Lets give a quick code review: 让我们快速回顾一下代码:

  • Read about java naming conventions. 了解有关Java命名约定的信息。 Method names go camelCase ; 方法名golCase ; and things that return boolean should be named like isPasswordValid() for example 例如,返回布尔值的东西应该命名为isPasswordValid()
  • What your are doing here is actually a good approach: one should prefer many small methods (that carry good meaningful names!) over having a few large methods (the thing behind is called the "Single Layer of Abstraction" Principle) 您在这里所做的实际上是一种好方法:人们应该宁愿使用许多小型方法(带有良好的有意义的名称!),而不要使用几种大型方法(所谓的“抽象层”原理)
  • You could read about regular expressions in order to do most of that checking; 您可以阅读正则表达式以进行大多数检查。 especially checking for "ascii chars only" is a good candidate there! 特别是检查“仅ascii字符”是一个不错的选择! So even when your assignment says "dont use them"; 因此,即使您的作业说“不要使用它们”; you might want to learn how to use them. 可能想学习如何使用它们。 Just for your own learning progress! 只为您自己的学习进度! But as Kayaman pointed out, the Character class has many static helper methods for such checks; 但是正如Kayaman指出的那样, Character类具有许多用于此类检查的静态帮助器方法。 so there is no need to implement all of that manually. 因此无需手动实现所有这些功能。
  • Your code is "logically inconsistent". 您的代码“逻辑上不一致”。 Your code is validating if some string adheres to certain password rules (minimum length, minimum number of digits). 您的代码是否在验证某些字符串是否符合某些密码规则(最小长度,最小位数)。 But your messages are implying that this code is checking if a provided password is correct ; 但是您的消息暗示此代码正在检查提供的密码是否正确 like in: user enters his password, and then code checks if that password is known and matching a previously stored password. 如:输入用户的密码,然后代码检查该密码是否已知并与先前存储的密码匹配。 In that sense: make sure messages and code content are consistent! 从这个意义上讲:确保消息和代码内容一致!

Beyond that; 除此之外; a suggestion how to enhance your design for "real world" usage. 有关如何针对“真实世界”用法增强设计的建议。 Thing is: there can be many many different rules that make a password valid . 事实是:可以有许多不同的规则来使密码有效 Which might change over time. 这可能会随着时间而改变。 And typically, you would want to tell your user which of that rules his input is conflicting with. 通常,您可能想告诉用户其输入与哪个规则冲突。 One option to address these concerns: 解决这些问题的一种选择:

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

Then you create various implementations, such as 然后您创建各种实现,例如

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

And then, you create instances of those different validator classes; 然后,创建这些不同的验证器类的实例。 and store them in some array. 并将它们存储在某个数组中。 You iterate the array, and call each validation on its own; 您对数组进行迭代,并单独调用每个验证。 and when it fails, you directly receive an exception with a nice message for the user. 当它失败时,您会直接收到一个异常,并向用户显示一条好消息。

As said: the above is meant as inspiration only (and just typed down, so beware of typos). 如前所述:上面的内容仅供参考(只需键入以下内容,请注意输入错误)。

Look at below code which may fulfill your all requirements- 请看下面的代码,它可以满足您的所有要求-

This is pure java class. 这是纯Java类。 you can check logic from the below code. 您可以从以下代码检查逻辑。

program edit1 - To specify why password is incorrect. 程序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++;
        }
    }
}

Now only you need to replace JOptionPane.showInputDialog() method with some other method which only specify message because showInputDialog() method prompts input text field also to enter value and we don't want this. 现在只需要用其他仅指定消息的方法替换JOptionPane.showInputDialog()方法,因为showInputDialog()方法会提示输入文本字段也输入值,我们不希望这样做。 I don't have idea any idea about swing. 我对挥杆一无所知。

Based on your comment - 根据您的评论-

This method returning string values like success,length,alphanumeric,digit ect. 此方法返回字符串值,例如成功,长度,字母数字,数字等。 and below we are comparing this values with all above in if else if. 下面我们将这个值与if if if上面的所有值进行比较。 whenever it get equal that means we have to show length message ,alphanumeric string message ,digit message accordingly. 每当它相等时,这意味着我们必须相应地显示长度消息,字母数字字符串消息,数字消息。

Dependency - 依赖-

I'm using maven. 我正在使用Maven。 following dependency need to add into pom.xml file. 以下依赖项需要添加到pom.xml文件中。

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

If you are not aware about maven then simply download jar file from here and provide in lib folder of your project. 如果您不了解maven,则只需从此处下载jar文件,并在项目的lib文件夹中提供即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM