微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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
}

如何设置该方法的值?

解决方法

您被允许拥有多个返回语句,因此写入是合法的
if (some_condition) {
  return true;
}
return false;

将布尔值与true或false进行比较也是不必要的,因此可以写入

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;

原文地址:https://www.jb51.cc/java/124900.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐