繁体   English   中英

如何在java中返回一个布尔方法?

[英]How to return a boolean method in java?

我需要有关如何在 Java 中返回布尔方法的帮助。 这是示例代码:

public boolean verifyPwd(){
        if (!(pword.equals(pwdRetypePwd.getText()))){
                  txtaError.setEditable(true);
                  txtaError.setText("*Password didn't match!");
                  txtaError.setForeground(Color.red);
                  txtaError.setEditable(false);
           }
        else {
            addNewUser();
        }
        return //what?
}

我希望verifyPwd()在我想调用该方法时返回一个 true 或 false 值。 我想这样调用该方法:

if (verifyPwd()==true){
    //do task
}
else {
    //do task
}

如何设置该方法的值?

你可以有多个return语句,所以写是合法的

if (some_condition) {
  return true;
}
return false;

也没有必要将布尔值与truefalse进行比较,因此您可以编写

if (verifyPwd())  {
  // do_task
}

编辑:有时你不能早点回来,因为还有更多的工作要做。 在这种情况下,您可以声明一个布尔变量并在条件块内适当地设置它。

boolean success = true;

if (some_condition) {
  // Handle the condition.
  success = false;
} else if (some_other_condition) {
  // Handle the other condition.
  success = false;
}
if (another_condition) {
  // Handle the third condition.
}

// Do some more critical things.

return success;

试试这个:

public boolean verifyPwd(){
        if (!(pword.equals(pwdRetypePwd.getText()))){
                  txtaError.setEditable(true);
                  txtaError.setText("*Password didn't match!");
                  txtaError.setForeground(Color.red);
                  txtaError.setEditable(false);
                  return false;
           }
        else {
            return true;
        }
        
}

if (verifyPwd()==true){
    addNewUser();
}
else {
    // passwords do not match

System.out.println("密码不匹配"); }

public boolean verifyPwd(){
        if (!(pword.equals(pwdRetypePwd.getText()))){
                  txtaError.setEditable(true);
                  txtaError.setText("*Password didn't match!");
                  txtaError.setForeground(Color.red);
                  txtaError.setEditable(false);
                  return false;
           }
        else {
            addNewUser();
            return true;
        }
}

为了可读性,您也可以这样做

boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());

if(!passwordVerified ){
    txtaError.setEditable(true);
    txtaError.setText("*Password didn't match!");
    txtaError.setForeground(Color.red);
    txtaError.setEditable(false);
}else{
    addNewUser();
}
return passwordVerified;

最好的方法是在代码块中声明Boolean变量并在代码结束时return它,如下所示:

public boolean Test(){
    boolean booleanFlag= true; 
    if (A>B)
    {booleanFlag= true;}
    else 
    {booleanFlag = false;}
    return booleanFlag;

}

我觉得这是最好的方法。

暂无
暂无

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

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