我需要帮助如何在
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;