2016-06-15 4 views
1

if 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; 
} 

저는 새로운 프로그래밍 언어를 배우려고합니다. 나는 'else'문이 if 조건이 거짓 일 때 항상 예외를 수행한다는 것을 읽었다. 이러한 거짓 경우

이제 :

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"); 

나는이 방법은 참/거짓 반환되기 때문에이 문제를 발견하고는 위의 조건이 거짓 경우에도 다른 부분을 무시하는 것처럼 보인다. 코드 exists(String name)의 휴식과 hTable ( Map<String,? extends Object>)의 종류에 대한 지식없이

+0

[최소, 완료 및 확인 가능한 예제] (http://stackoverflow.com/help/mcve)를 게시 하시겠습니까? – MikeCAT

+0

'else'는 다른 모든 조건문 (예 : 'if','else else'는'false'입니다. * 항상 * 실행되지 않습니다. 다음과 같이 생각하십시오. '비가 오면 우산을 가져 간다. 그렇지 않으면 눈이 오면 내 파카를 입는다. 그렇지 않으면 반바지와 티셔츠를 입습니다. ' –

+0

이들은 중첩되지 않습니다. 순서가 정해져 있습니다. 당신의 두 번째는 당신의 두 번째와 함께 간다. ''Animal does not exist ''를 원한다면,''exists (name)''는 처음 if 조건의 조건이 아니라 false가 될 필요가 있습니다. – Gendarme

답변

1

것 같아요해야합니다

종료가 true를 돌려주는 경우, else 문이 true로 평가합니다. hTable.remove (name) 행이 실행됩니다. else if이 있었으므로 else-branch가 호출되지 않습니다. 이제 마지막 줄은 return hTable.get(name) == null;

hTable이 null을 반환하기 때문에 true를 반환한다고 생각합니다.

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 
} 

는 의견은 당신이 흐름을 이해하는 데 도움이 희망 :

1

난 당신이 흐름을 이해하는 데 도움이 당신의 조각에 주석을 추가하려고합니다!

이 점을 염두에두고 귀하의 질문에 대한 답변은 '예'입니다.

관련 문제