2016-06-15 2 views
1

私はelse文を含むメソッドを作成していますが、returnキーワードも書いています。今、私はこのようなものを書いている:Java:if、elseとreturn

public boolean deleteAnimal(String name) throws Exception{ 
    if(name == null || name.trim().isEmpty()) 
     throw new Exception("The key is empty"); 
    else if(exists(name)){ 
     hTable.remove(name); 
    } 
    else throw new Exception("Animal doesn't exist"); 

    return hTable.get(name) == null; 
} 

は、私はJavaで新たなんだ、これはプログラミング言語を習得しようとしている私の最初の時間です。 if条件が偽であれば、else文は常に実行されます。これらが偽である場合

今、:

if(name == null || name.trim().isEmpty()) 
     throw new Exception("The key is empty"); 
    else if(exists(name)){ 
     hTable.remove(name); 
} 

は他の部分は常にexcecuteべきではないでしょうか。

else throw new Exception("Animal doesn't exist"); 

は、私は、このメソッドがfalse/trueを返しているので、これに気づいて、それ以上の条件が偽である場合でも、それ以外の部分を無視しているように思えます。コード exists(String name)の残りと hTableMap<String,? extends Object>)のタイプについての知識がなくても

+0

[最小限で完全であり、検証可能な例](http://stackoverflow.com/help/mcve)を投稿してもよろしいですか? – MikeCAT

+0

「else」は、他のすべての条件、 'if'、' else else'は 'false'です。常に*実行するわけではありません。それについてこう考えてください。「雨が降ったら、私は傘を持っていきます。そうでなければ雪が降っていると、私は自分のパーカを着ます。そうでなければ、私はショーツとTシャツを着用します。 ' –

+0

これらはネストされていません。それらは配列決定される。あなたの第二のものはあなたの第二のものと一緒に行く。 '' Animal does not exist '''を望むなら、 '' exists(name) ''は最初のif条件の条件ではなく、偽である必要があります。 @KennethK。 – Gendarme

答えて

1

私が推測する必要があります。

終了がtrueを返した場合、else文が真と評価された場合。行hTable.remove(name)が実行されます。 elseブランチは、else ifであったため、呼び出されません。最後の行はreturn hTable.get(name) == null;

となります。hTableはnullを返すため、trueを返します。

1

私はあなたが流れを理解するために、あなたのスニペットにコメントを追加しようとするでしょう:

public boolean deleteAnimal(String name) throws Exception{ 
    if(name == null || name.trim().isEmpty()) 
     throw new Exception("The key is empty"); //Executes if 'name' is null or empty 

    else if(exists(name)){ 
     hTable.remove(name);  // Excecutes if 'name' is not null and not empty and the exists() returns true 
    } 

    else 
     throw new Exception("Animal doesn't exist"); //Excecutes if 'name' is not null and not empty and the exists() returns false 

    return hTable.get(name) == null; //The only instance when this is possible is when the 'else if' part was executed 
} 

はコメントはあなたが流れを理解するのに役立ちます願っています!

これを念頭に置いて、あなたの質問に対する答えは「はい」です。

関連する問題