如何在java中返回一个布尔方法?

前端之家收集整理的这篇文章主要介绍了如何在java中返回一个布尔方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要帮助如何在 java中返回一个布尔方法.这是示例代码
  1. public boolean verifyPwd(){
  2. if (!(pword.equals(pwdRetypePwd.getText()))){
  3. txtaError.setEditable(true);
  4. txtaError.setText("*Password didn't match!");
  5. txtaError.setForeground(Color.red);
  6. txtaError.setEditable(false);
  7. }
  8. else {
  9. addNewUser();
  10. }
  11. return //what?
  12. }

我想要在我想要调用方法时,verifyPwd()返回一个true或false值.我想这样调用方法

  1. if (verifyPwd()==true){
  2. //do task
  3. }
  4. else {
  5. //do task
  6. }

如何设置该方法的值?

解决方法

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

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

  1. if (verifyPwd()) {
  2. // do_task
  3. }

编辑:有时你不能早点回来,因为还有更多的工作要做.在这种情况下,您可以声明一个布尔变量并在条件块内进行适当的设置.

  1. boolean success = true;
  2.  
  3. if (some_condition) {
  4. // Handle the condition.
  5. success = false;
  6. } else if (some_other_condition) {
  7. // Handle the other condition.
  8. success = false;
  9. }
  10. if (another_condition) {
  11. // Handle the third condition.
  12. }
  13.  
  14. // Do some more critical things.
  15.  
  16. return success;

猜你在找的Java相关文章