25

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
}

そのメソッドの値を設定するにはどうすればよいですか?

4

5 に答える 5

24

複数の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;
于 2013-01-21T03:31:58.097 に答える
7

これを試して:

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( "パスワードが一致しません"); }

于 2013-01-21T03:32:55.240 に答える
3
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;
        }
}
于 2013-01-21T03:32:33.397 に答える
3

読みやすくするために、これを行うこともできます

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;
于 2013-01-21T03:36:06.083 に答える
1

Boolean最良の方法は、次のように、コードブロック内で変数を宣言し、コードreturnの最後で変数を宣言することです。

public boolean Test(){
    boolean booleanFlag= true; 
    if (A>B)
    {booleanFlag= true;}
    else 
    {booleanFlag = false;}
    return booleanFlag;

}

これが最善の方法だと思います。

于 2016-11-07T16:39:46.163 に答える