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

时间:2013-01-21 03:27:45

标签: java function methods boolean

我需要有关如何在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
}

如何设置该方法的值?

5 个答案:

答案 0 :(得分:21)

您被允许拥有多个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;

答案 1 :(得分:5)

试试这个:

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
}

答案 2 :(得分:2)

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

答案 3 :(得分:2)

为了便于阅读,你也可以这样做

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;

答案 4 :(得分:0)

最好的方法是在代码块中声明Boolean变量,在代码末尾声明return,如下所示:

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

}

我发现这是最好的方式。

相关问题