본문 바로가기
Java (자바)

쉽게 따라하는 Java (자바) 독학 _ 제어문 _ 조건문 (if)

by Ecoder 2022. 12. 6.

Java (자바) 제어문 _ 조건문 (if) 

 

1. 조건문 if

   - 주어진 조건에 따라 해당 조건이 참(true) 일 때 명령을 수행

   

   - if문 관련 명령어

       1) if: 해당 조건이 true일 때 명령을 수행

       2) else if: 위의 조건들이 모두 false이고, 해당 조건이 true일 때 명령 수행

       3) else: 위의 조건들이 모두 false일 때 명령 수행

 

   - if문 관련 명령어 조합 (3가지)

       1) if 단독 사용

       2) if + else

       3) if + else if + else

   

   - if문 사용 형태

         if (조건식1) {

              true일때 수행할 작업들

          }

         else if (조건식 2) {

              조건식 1이 false이고 조건식 2가 true일 때 수행할 작업들

         }

         else if (조건식 3) {

              조건식 1,2가 false이고 조건식3이 true일 때 수행할 작업들

         }

         else {

              조건식 1,2,3이 false일때 수행할 작업들

         }

 

 

2. 조건문 if Test

 

Class Name: IfTest_01

public static void main(String[] args) 체크

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
public class IfTest_01 {
 
    public static void main(String[] args) {
        int age = 3;
        int charge = 12000;
 
        if(age < 7) {
            System.out.println("할인 대상입니다.");
            charge = charge - 5000;
        }
 
        else if (age > 60) {
            System.out.println("할인 대상입니다.");
            charge = charge - 8000;
        }
 
        else {
            System.out.println("할인 대상이 아닙니다.");
        }
 
 
        System.out.printf("지불요금: %,d원%n", charge);
 
    }
 
}
 
cs

코드 작성

 

 

저장(ctrl + s) 후 F11을 눌러 출력되는 내용 확인하기

 

 

3. 테스트 해 보세요

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
public class IfTest_01 {
 
    public static void main(String[] args) {
        String name = "홍길동";
        int kor = 92, eng = 83, mat = 88;
        int total = kor + eng + mat;
        double avg = total / 3.0;
        String result = null;
        
        if(avg>= 90) {
            result = "A학점";
        }
        else if(avg >=80) {
            result = "B학점";
        }
        else if(avg >=70) {
            result = "C학점";
        }
        else if(avg >=60) {
            result = "D학점";
        }
        else {
            result = "F학점";
        }
 
        System.out.printf("%s 학생의 평균은 %.2f점이고, %s 입니다.", name, avg, result);
    }
}
cs

 

 

4. 과제

데이터 입력 받기(Scanner), 형식화된 출력문 (Printf) 과제에 하기 내용의 형식에 맞게 코드를 수정해보세요.

 

  BMI 단계별 용어

    - 18.5 미만이면 저체중

    - 18.5∼22.9는 정상

    - 23 ~ 24.9는 비만 전 단계

    - 25∼29.9는 '1단계 비만'

    - 30∼34.9는 '2단계 비만'

    - 35 이상이면 '3단계 비만'

 

xxx(이름) 회원님의 BMI는 xxx이고, xxx(BMI 단계별 용어) 상태입니다.

 

 

반응형

댓글