How to return a boolean method in Java?
•
Java
I need help on how to return a boolean method in Java Here 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 verifypwd () to return a true or false value when I want to call this method I want to call the method like this:
if (verifyPwd()==true){
//do task
}
else {
//do task
}
How to set the value of this method?
Solution
You are allowed to have multiple return statements, so writing is legal
if (some_condition) {
return true;
}
return false;
Comparing Boolean values to true or false is also unnecessary, so you can write
if (verifyPwd()) {
// do_task
}
Editor: sometimes you can't come back early because there's more work to do In this case, you can declare a boolean variable and set it appropriately in the condition block
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;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
