[英]How to return a boolean method in java?
I need help on how to return a boolean method in java.我需要有关如何在 Java 中返回布尔方法的帮助。 This is the sample code:这是示例代码:
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?
}
I want the verifyPwd()
to return a value on either true or false whenever I want to call that method.我希望verifyPwd()
在我想调用该方法时返回一个 true 或 false 值。 I want to call that method like this:我想这样调用该方法:
if (verifyPwd()==true){
//do task
}
else {
//do task
}
How to set the value for that method?如何设置该方法的值?
You're allowed to have more than one return
statement, so it's legal to write你可以有多个return
语句,所以写是合法的
if (some_condition) {
return true;
}
return false;
It's also unnecessary to compare boolean values to true
or false
, so you can write也没有必要将布尔值与true
或false
进行比较,因此您可以编写
if (verifyPwd()) {
// do_task
}
Edit: Sometimes you can't return early because there's more work to be done.编辑:有时你不能早点回来,因为还有更多的工作要做。 In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.在这种情况下,您可以声明一个布尔变量并在条件块内适当地设置它。
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;
try this:试试这个:
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("password 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;
}
}
You can also do this, for readability's sake为了可读性,您也可以这样做
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;
Best way would be to declare Boolean
variable within the code block and return
it at end of code, like this:最好的方法是在代码块中声明Boolean
变量并在代码结束时return
它,如下所示:
public boolean Test(){
boolean booleanFlag= true;
if (A>B)
{booleanFlag= true;}
else
{booleanFlag = false;}
return booleanFlag;
}
I find this the best way.我觉得这是最好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.