문제

다음과 같은 명세서 블록이있는 경우 :

if (/*condition here*/){ }
else{ }

또는 이렇게 :

if (/*condition here*/)
else if (/*condition here*/) {}
else if (/*condition here*/) {}

차이점은 무엇입니까?

if/else에서는 부품이 실제 상태이고 다른 부분이 다른 모든 가능한 옵션 (false)에 대한 것 같습니다. 다른 조건에 유용 할 것입니다. 이것은 내 이해입니다. 더 알아야 할 것이 더 있습니까?

도움이 되었습니까?

해결책

상황 A :

if( condition )
{
}
else
{
}

위의 진술의 조건이 False 인 경우 Else 블록의 진술은 항상 실행됩니다.

상황 B :

if( condition )
{
}
else if( condition2 )
{
}
else
{
}

'조건'이 false 인 경우, 다른 경우 블록의 진술은 조건 2가 참일 때만 실행됩니다. Else 블록의 진술은 Condition2가 False 일 때 실행됩니다.

다른 팁

"elseif"구문이 없으면 가능한 몇 가지 가능한 결과 중 하나를 처리하기 위해 체인 if 진술을 작성해야합니다.

if( str == "string1" ) {
   //handle first case
} else {
    if( str == "string2" ) {
       //handle second case
    } else {
       if( str == "string3" ) {
           //handle third case
       } else {
          //default case
       }
    }
 }

대신 당신은 쓸 수 있습니다

if( str == "string1" ) {
   //handle first case
} else if( str == "string2" ) {
   //handle second case
} else if( str == "string3" ) {
   //handle third case
} else {
   //default case
}

그것은 이전과 완전히 동일하지만 훨씬 더 멋져 보이고 읽기가 훨씬 쉽습니다.

많은 언어에는 이와 같은 그레이머가 있습니다 (여기 : ecmascript 언어 사양, so javaScript) :

ifstatement :
    if ( 표현 ) 성명 else 성명
    if ( 표현 ) 성명

성명 :
    차단하다
    변수
    빈 상태
    표현식
    ifstatement
    반복 조치
    연속
    브레이크 스테이트
    반환 체계
    withstatement
    레이블 스테이트
    스위치 스테이트
    던지기
    시도

차단하다 :
    { StatementList고르다 }

StatementList :
    성명
    StatementList 성명

그래서 an의 가지 ifstatement 진술 블록을 포함 할 수 있습니다 (차단하다) 또는 다른 진술 중 하나 (다른 말 차단하다). 즉, 이것이 유효하다는 것을 의미합니다.

if (expr)
    someStatement;
else
    otherStatement;

그리고 AS StatementList 단일 진술 만 포함 할 수 있습니다.이 예제는 이전과 동일합니다.

if (expr) {
    someStatement;
} else {
    otherStatement;
}

if (expr)
    someStatement;
else {
    otherStatement;
}

if (expr) {
    someStatement;
} else
    otherStatement;

그리고 우리가 교체 할 때 otherStatement 추가로 ifstatement, 우리는 이것을 얻습니다 :

if (expr) {
    someStatement;
} else
    if (expr) {
        someOtherStatement;
    }

나머지는 단지 코드 형식입니다.

if (expr) {
    someStatement;
} else if (expr) {
    someOtherStatement;
}

Gumbo가 말한 것을 강조합니다.

또한 언어에 실제 elif / elsif / elseif가있는 경우 (예 : 형식에 의해 숨겨져있는 일종의 중첩 된 체인 대신), 컴파일러는 초록에서 단일 노드를 쉽게 방출 할 수 있습니다. 구문 트리 (또는 이와 유사한, 참조 http://en.wikipedia.org/wiki/abstract_syntax_tree) 둥지를 짓는 대신.

예를 들어 보려면 :

C/C ++에서 다음과 같이 말합니다.

if (a) {
    X
} else if (b) {
    Y
} else if (c) {
    Z
} else {
    0
}

그런 다음 컴파일러는 다음과 같은 AST 노드를 구축합니다.

   a
  / \
 X   b
    / \
   Y   c
      / \
     Z   0

그러나 선택 언어에 실제 if-else가 있다면 :

if (a) {
    X
} elif (b) {
    Y
} elif (c) {
    Z
} else {
    0
}

AST는 다음과 같이 더 쉽게 보일 수 있습니다.

   (a--b--c)
   /  /  /  \
  X  Y  Z    0

그러한 언어로, "다른 경우"는 버팀대가 필수가 아닌 경우에만 가능합니다.

if (a) {
    X
} elif (b) {
    Y
} else if (c) {  // syntax error "missing braces" if braces mandatory
    Z
} else {
    0
}

해당 AST (버팀대가 필수가 아닌 경우):

   (a--b)
   /  /  \
  X  Y    c
         / \
        Z   0

이것은 CFG 분석을 만들 수 있습니다 (http://en.wikipedia.org/wiki/control_flow_graph) 더 쉽습니다 구현하다 (실제 최적화 이점은 없을 수도 있지만 IMHO는 게으른 프로그래머에게 도움이 될 것입니다 : D).

else if 기본적으로 else 부분의 if 또 다른 것입니다 if 성명.

**if/else**
if(condition)
  statement;
else
   statement;

if / else / else

if(condition)
 {
   if(condition)
      statement;
   else 
     statement;
  }   
else if(condition)
{
    if(condition)
     statement;
    else
     statement;
}
else
    statement;

if/else 및 if/else에서도 사용되는 경우

단일 변수가 주어지면 단순한 if-else 구조. 여러 변수가 있고 다른 가능성을 위해 실행할 경로가 다른 경우 사용합니다. if-else if-...-else. 후자는 또한 끝납니다 else 성명.

당신은 이미 스스로 답을 주었다. /else는 true/false result에 대한 경우, int = 2 또는 다른 가능한 int 값이며,/elseif는 int = 2, int = 3 등과 같은 2 개 이상의 결과에 대한 것입니다.

또한 변수의 컨텍스트를 그룹화합니다. 같은 모든 결과를 확인할 수 있습니다

if (a == 2) { do one thing };
if (a == 3) { do another thing };
...
if (a != 2 && a != 3 ...) { do something else };

if/else/elseif를 사용하면 읽을 수 있습니다.

더 많은 조건을 확인하려면 if..elseif를 사용할 수 있습니다. 그런 다음 단일 조건은 IF 또는 IF ... 다른 경우 사용할 수 있습니다.

여기서는 예제로 전체 설명을 업로드 할 수 없으므로 다음 링크를 살펴보십시오.

if.... 진술서 세부 사항
http://allinworld99.blogspot.in/2016/02/ifelse-flow-chart-with-easy-example.html
if ... elseif 세부 사항
http://allinworld99.blogspot.in/2016/02/flow-chart-with-example-for-if-then.html

import java.util.*;

public class JavaApplication21 {
    public static void main(String[] args) {

        Scanner obj = new Scanner(System.in);
        System.out.println("You are watching an example of if & else if statements");

        int choice, a, b, c, d;
        System.out.println(" Enter 1-Addition & 2-Substraction");

        int option = obj.nextInt();
        switch (option) {
            case (1):
                System.out.println("how many numbers you want to add.... it can add up to 3 numbers only");
                choice = obj.nextInt();
                if (choice == 2) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    c = a + b;

                    System.out.println("Answer of adding " + a + " & " + b + " is= " + c);
                } else if (choice == 3) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    System.out.println("Enter 3rd number");
                    c = obj.nextInt();

                    d = a + b + c;

                    System.out.println("Answer of adding " + a + " , " + b + " & " + c + "  is= " + d);
                }
            case (2):
                System.out.println("how many numbers you want to substract.... it can substract up to 3 numbers only");
                choice = obj.nextInt();
                if (choice == 2) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    c = a - b;
                    System.out.println("Answer of substracting " + a + " & " + b + " is= " + c);
                } else if (choice == 3) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    System.out.println("Enter 3rd number");
                    c = obj.nextInt();

                    d = a - b - c;
                    System.out.println("Answer of substracting " + a + " , " + b + " & " + c + "  is= " + d);
                }
            default:
                System.out.println("no option you have chosen" + option);
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top