如何在java中返回布尔方法?
我需要关于如何在java中返回布尔方法的帮助。这是示例代码:如何在java中返回布尔方法?,java,function,methods,boolean,Java,Function,Methods,Boolean,我需要关于如何在java中返回布尔方法的帮助。这是示例代码: public boolean verifyPwd(){ if (!(pword.equals(pwdRetypePwd.getText()))){ txtaError.setEditable(true); txtaError.setText("*Password didn't match!"); txtaErro
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
}
public boolean Test(){
boolean booleanFlag= true;
if (A>B)
{booleanFlag= true;}
else
{booleanFlag = false;}
return booleanFlag;
}
如何设置该方法的值 您可以有多个
return
语句,因此编写
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;
试试这个:
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(“密码不匹配”);
}为了可读性,您也可以这样做
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
变量,并在代码末尾返回它,如下所示:
if (verifyPwd()==true){
//do task
}
else {
//do task
}
public boolean Test(){
boolean booleanFlag= true;
if (A>B)
{booleanFlag= true;}
else
{booleanFlag = false;}
return booleanFlag;
}
我觉得这是最好的方法。为什么对一个完全有效的问题投反对票,而这个问题可能对其他开始学习的人有帮助?谁知道在什么情况下你想要回报什么?…因为没有人提到:
==true
部分是毫无意义的。该方法已经返回了一个boolean
,因此if(verifyPwd())
是完全有效的if
语句。如果仔细选择方法名称,以产生一个漂亮的句子,如if(passwordRetypeMatches())
,那么它也是完全可读的。此外,我要避免在一个名称中只有验证或匹配的方法中使用太多逻辑:这种逻辑应该在外部完成,很可能在if-else分支中完成。我知道这是在他的原始代码中,但是当if
块以return
结束时,没有理由使用else
,也没有必要将布尔值与true进行比较。@JayMarz什么是递归的?