0

こんにちは、これは私がプロジェクト用に作成したコードで、他のいくつかのメソッドを呼び出して、その人物に関する声明を出力します。私の問題は二重に印刷され、両方の if/else ステートメントを実行しているようです。

どうすればこれを防ぐことができますか? 必要に応じて、端末からテキストを追加できます。以下のコード。

 void printPersonDescription(String name, boolean sex, int age) {

    if(sex == true && yearsUntilNextMaturityLevel(age) > 1) {
        println (name + " is " + getMaturityLevel(age) + ". " + "At " + age + 
        " she has " + yearsUntilNextMaturityLevel(age) + " years left until she is " + 
        nextMaturityLevel(age) + "."); 
    }
    else if(sex == false && yearsUntilNextMaturityLevel(age) > 1) {
        println (name + " is " + getMaturityLevel(age) + ". " + "At " + age + 
        " he has " + yearsUntilNextMaturityLevel(age) + " years left until he is " + 
        nextMaturityLevel(age) + ".");
    }
    if (sex == true && yearsUntilNextMaturityLevel(age) <= 1) {
        println (name + " is " + getMaturityLevel(age) + ". " + "At " + age + 
        " she has " + yearsUntilNextMaturityLevel(age) + " year left until she is " + 
        nextMaturityLevel(age) + "."); 
    }
    else {
        println (name + " is " + getMaturityLevel(age) + ". " + "At " + age + 
        " he has " + yearsUntilNextMaturityLevel(age) + " year left until he is " + 
        nextMaturityLevel(age) + ".");
    }

}
4

3 に答える 3

0
 void printPersonDescription(String name, boolean sex, int age) {

    if(sex == true && yearsUntilNextMaturityLevel(age) > 1) {
        println (name + " is " + getMaturityLevel(age) + ". " + "At " + age + 
        " she has " + yearsUntilNextMaturityLevel(age) + " years left until she is " + 
        nextMaturityLevel(age) + "."); 
    }
    else if(sex == false && yearsUntilNextMaturityLevel(age) > 1) {
        println (name + " is " + getMaturityLevel(age) + ". " + "At " + age + 
        " he has " + yearsUntilNextMaturityLevel(age) + " years left until he is " + 
        nextMaturityLevel(age) + ".");
    }
    else if (sex == true && yearsUntilNextMaturityLevel(age) <= 1) {    
        println (name + " is " + getMaturityLevel(age) + ". " + "At " + age + 
        " she has " + yearsUntilNextMaturityLevel(age) + " year left until she is " + 
        nextMaturityLevel(age) + "."); 
    }
    else {
        println (name + " is " + getMaturityLevel(age) + ". " + "At " + age + 
        " he has " + yearsUntilNextMaturityLevel(age) + " year left until he is " + 
        nextMaturityLevel(age) + ".");
    }

}

else3 番目の前に追加する必要がありますif。それ以外の場合、最後のelseステートメントは 3 番目のステートメントと一致するifため、else ステートメントは次のことを意味します。

if(sex != true || yearsUntilNextMaturityLevel(age) > 1)
于 2013-09-25T07:57:17.113 に答える