我是否正确地使用这些布尔方法

时间:2013-06-12 17:50:38

标签: java methods boolean

设计一个名为Password2的类,如以下UML图中所指定: enter image description here

  
      
  • 密码必须至少包含七个字符
  •   
  • 密码仅包含字母和数字
  •   
  • 密码必须至少包含三位数字
  •   
     

+Password2 (ps: String)输入密码的构造

     

+verifyPassword2():void调用其他支持方法

     

-verifyLength():boolean根据密码长度返回true / false

     

-verifyValidCharacters():boolean根据有效/无效字符返回true / false

     

-verifyNumberOfDigits(): boolean根据位数

返回true / false      

+printReport():void按照以下规定打印摘要报告

这是我到目前为止所做的:

public class Password2 {
private boolean rule1;
private boolean rule2;
private boolean rule3;
private String ps;

public Password2(){
}

 public Password2(String ps){
     this.ps = ps;
 }

 public void verifyPassword2(){
     //Verify the password is the right length
     rule1 = verifyLength();
     rule2 = verifyValidCharacters();
     rule3 = verifyNumberOfDigits();
}    
private boolean verifyLength(){
         if (ps.length() >= 8){
             return true;
        return false;
    }
     //Verify if the password have the right characters
private boolean verifyValidCharacters(){
    if (ps.matches("^[A-Za-z1-9]$"){
        return true;}
    return false;    
    }
     //Verify if the password contains at least 2 digits
private boolean verifyNumberOfDigits(){
    int digit = 0;
    for (int i = 0; i = <ps.length(); i++){
        char letter = password.charAt(i);
        if(Character.isDigit(letter)){
                digit++;
                    }
         if (digits >= 2){
            return true;{
                    }
         return false
         }
     }

 public void printReport(){
     String Report;
     Report = "\t+++++++++++++++++ Password Report ++++++++++++++++++++\n";
     Report += "\tLebron Broadnax\n";
     Report += "\tCS1302\n";
     Report += "\t6/11/201\n3";
     Report += "\t+++++++++++++++++++++++++++++++++++++++++++++++++++++";

 }
 }

这些方法不在其他方法中。这就是我发布它的方式

1 个答案:

答案 0 :(得分:1)

改进的一个提示:

//Verify if the password have the right characters
private boolean verifyValidCharacters()
{
     if (ps.matches("^[A-Za-z1-9]$")
         return true;

    return false;
}

可以更改为:

private boolean verifyValidCharacters()
{
     return ps.matches("^[A-Za-z1-9]$");
}

如果匹配则返回true,如果不匹配则返回false,这正是matches(regex)所做的。

类似的逻辑可以应用于:

  private boolean verifyNumberOfDigits()
  {
       int digit = 0;

       for (int i = 0; i = <ps.length(); i++)
       {
            char letter = password.charAt(i);

            if(Character.isDigit(letter))
                digit++;
       }            

       return (digit >= 2);             
 }

此外,不应在verifyPassword2方法中声明您的方法。

您应该将问题发布到:codereview.stackexchange