2013-01-21 7 views
13

私はJavaでブールメソッドを返す方法について助けが必要です。これはサンプルコードです: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 
} 

どのように値を設定するのですか?

+8

なぜ学ぶのを始めている他の人に役立つ完全に有効な質問のためのdownvote? –

+0

あなたはどんな状況のために何を返そうとしているのか知っていますか?... –

答えて

18

あなたが複数のreturnステートメントを持つことが許されているので、それはあなたが

if (verifyPwd()) { 
    // do_task 
} 
を書くことができますので、それは、 trueまたは falseにブール値を比較することも不要です

if (some_condition) { 
    return true; 
} 
return false; 

を書くために法的です


編集:完了する作業が増えているため、早期返却できないことがあります。その場合、ブール変数を宣言し、条件ブロック内で適切に設定することができます。

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; 
1
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; 
     } 
} 
+0

なぜdownvoteですか?ちょうど私は間違いがどこにあったかを知ることができます。 –

4

これを試してみてくださいそれはコードの最後に、次のようになります:

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

} 

これが最良の方法です。

+0

私はそれが元のコードであることを知っていますが、 'if'ブロックが' return'で終わったときに 'else'を持つ必要はなく、真とブール値を比較する必要はありません。 –

2

あなたはまた、読みやすさのために、これを行うことができます。

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; 
+0

は再帰的ではありませんか? –

+1

@JayMarz何が再帰的ですか? –

0

最良の方法は、コードブロックとreturnBoolean変数を宣言するだろう

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 
} 
関連する問題