1. if진술 의 순서

때때로 프로그램은 변수 값이나 식 값에 따라 다양한 작업을 수행해야 합니다.

우리의 작업이 다음과 같다고 합시다.

  • 온도가 도보다 높으면 20셔츠를 입으십시오.
  • 온도가 도보다 크고 10작으면 20스웨터를 입으십시오.
  • 온도가 도보다 크고 0작으면 비옷 10을 입으십시오.
  • 온도가 도 미만이면 0코트를 입으십시오.

이것이 코드로 표현되는 방법은 다음과 같습니다.

int temperature = 9;

if (temperature > 20) {
   System.out.println("put on a shirt");
} else { // Here the temperature is less than (or equal to) 20
   if (temperature > 10) {
      System.out.println("put on a sweater");
   } else { // Here the temperature is less than (or equal to) 10
      if (temperature > 0) {
         System.out.println("put on a raincoat");
      } else // Here the temperature is less than 0
         System.out.println("put on a coat");
   }
}

If-else명령문은 서로 중첩될 수 있습니다 . 이를 통해 프로그램에서 다소 복잡한 논리를 구현할 수 있습니다.

그러나 프로그래머는 일반적으로 이 구문을 약간 다르게 작성합니다.

int temperature = 9;

if (temperature > 20) {
   System.out.println("put on a shirt");
} else if (temperature > 10) { // Here the temperature is less than (or equal to) 20
   System.out.println("put on a sweater");
} else if (temperature > 0) { // Here the temperature is less than (or equal to) 10
   System.out.println("put on a raincoat");
} else { // Here the temperature is less than 0
   System.out.println("put on a coat");
}

주어진 두 가지 예는 동일하지만 두 번째 예가 이해하기 더 쉽습니다.


2. else블록 의 뉘앙스

중요한 점:

구성 에서 중괄호를 사용하지 않으면 if-elsethe 가 else가장 가까운 이전 을 참조합니다 if.

예:

우리의 코드 작동 방식
int age = 65;

if (age < 60)
   if (age > 20)
      System.out.println("You must work");
else
   System.out.println("You don't have to work");
int age = 65;

if (age < 60) {
   if (age > 20)
     System.out.println("You must work");
   else
     System.out.println("You don't have to work");
}

왼쪽의 코드를 보면 화면 출력이 "You don't have to work"일 것 같습니다. 하지만 그렇지 않습니다. 실제로 else블록과 "You don't have to work" 문은 두 번째(가까운) if문과 연결됩니다.

오른쪽 코드에서 관련 if및 가 else빨간색으로 강조 표시됩니다. 또한 중괄호는 모호하지 않게 배치되어 수행할 작업을 명확하게 보여줍니다. 일할 필요가 없습니다라는 문자열은 가 age보다 크면 표시되지 않습니다 60.


4
과제
Java Syntax,  레벨 4레슨 1
잠금
This age doesn't work for me…
Sometimes we all want to change our age. First, they don't want to sell you cigarettes or beer. Then your hair starts thinning and your back aches! A programmer may not have control over time, but he or she has total control over data in programs. In this task, we correct an error so that a Person object's age variable receives a different value.

if-else3. 스테이트먼트 사용 예

진술을 잘 살펴보았으므로 if-else예를 들어 보겠습니다.

import java.util.Scanner;
public class Solution {
   public static void main(String[] args) {
     Scanner console = new Scanner(System.in); // Create a Scanner object
     int a = console.nextInt(); // Read the first number from the keyboard
     int b = console.nextInt(); // Read the second number from the keyboard
     if (a < b)                   // If a is less than b
       System.out.println(a);     // we display a
     else                         // otherwise
       System.out.println(b);     // we display b
   }
}
최소 두 숫자 표시