[1주차] Java 기초 예습 - (3)

서연·2025년 4월 10일

Java

목록 보기
3/36

1. IF

if (조건식) {
ㅤㅤㅤㅤ조건식의 결과가 참일 때 실행하고자 하는 문장;
}

ex)

class Main {
    public static void main(String[] args) {
        char ch = 'b';
        if (ch >= 'a' && ch <= 'z') {
            System.out.println("해당 문자는 영문 소문자입니다.");
        }
    }
}

1. if - else

if (조건식) {
ㅤㅤㅤ조건식의 결과가 참일 때 실행하고자 하는 문장;
} else {
ㅤㅤㅤ조건식의 결과가 거짓일 때 실행하고자 하는 문장;
}

ex)

class Main {
    public static void main(String[] args) {
        char ch = 'Z';
        if (ch >= 'a' && ch <= 'z') {
            System.out.println("해당 문자는 영문 소문자입니다.");
        } else {
            System.out.println("해당 문자는 영문 소문자가 아닙니다.");
        }
    }
}

2. if - else if - else

if (조건식1) {
ㅤㅤㅤ조건식1의 결과가 참일 때 실행하고자 하는 문장;
} else if (조건식2) {
ㅤㅤㅤ조건식2의 결과가 참일 때 실행하고자 하는 문장;
} else {
ㅤㅤㅤ조건식1의 결과도 거짓이고, 조건식2의 결과도 거짓일 때 실행하고자 하는 문장;
ㅤㅤㅤ즉, 위의 어느 조건식에도 만족하지 않을 때 수행
}

  • 여러개의 조건식을 포함한 조건식
  • else if 가 여러번 사용 될 수 있음
  • 마지막 else 블럭은 생략 가능

ex)

class Main {
    public static void main(String[] args) {
        char ch = 'p';

        if (ch >= 'a' && ch <= 'z') {
            System.out.println("해당 문자는 영문 소문자입니다.");
        } else if (ch >= 'A' && ch <= 'Z') {
            System.out.println("해당 문자는 영문 대문자입니다.");
        } else {
            System.out.println("해당 문자는 영문자가 아닙니다.");
        }

        int score = 70;

        if (score >= 90) {
            System.out.println("A등급입니다.");
        } else if(score >= 80) {
            System.out.println("B등급입니다.");
        } else if(score >= 70) {
            System.out.println("C등급입니다.");
        }
    }
}

3. 중첩 if

if (조건식1) {
ㅤㅤㅤ조건식1의 결과가 참일 때 실행하고자 하는 문장;
ㅤㅤㅤif (조건식2) {
ㅤㅤㅤㅤㅤㅤ조건식1 과 조건식 2의 결과가 모두 참일 때 실행하고자 하는 문장;
ㅤㅤㅤ} else {
ㅤㅤㅤㅤㅤㅤ조건식1의 결과가 참이고, 조건식2의 결과가 거짓일 때 실행하고자 하는 문장;
ㅤㅤㅤ}
} else {
ㅤㅤㅤㅤ조건식1의 결과가 거짓일 때 실행하고자 하는 문장;
}

ex)

class Main {
    public static void main(String[] args) {
        int score = 87;

        if (score >= 90) {
            if(score >= 95){
                System.out.println("A++등급입니다.");
            }else {
                System.out.println("A등급입니다.");
            }
        } else if(score >= 80) {
            if(score >= 85){
                System.out.println("B++등급입니다.");
            }else {
                System.out.println("B등급입니다.");
            }
        } else if(score >= 70) {
            if(score >= 75){
                System.out.println("C++등급입니다.");
            }else {
                System.out.println("C등급입니다.");
            }
        }else {
            System.out.println("D등급입니다.");
        }
    }
}

2. SWITCH

switch (조건식) {
ㅤㅤㅤㅤㅤcase 값1:
ㅤㅤㅤㅤㅤㅤㅤㅤ조건식의 결과가 값1과 같을 경우 수행할 문장;
ㅤㅤㅤㅤㅤㅤㅤㅤbreak;
ㅤㅤㅤㅤㅤcase 값2:
ㅤㅤㅤㅤㅤㅤㅤㅤ조건식의 결과가 값2와 같을 경우 수행할 문장;
ㅤㅤㅤㅤㅤㅤㅤㅤbreak;
ㅤㅤㅤㅤㅤ....
ㅤㅤㅤㅤㅤdefault:
ㅤㅤㅤㅤㅤㅤㅤㅤ조건식의 결과와 일치하는 case 문이 없을 때 수행할 문장;
}

  • 처리해야 하는 경우의 수가 많을 때 유용한 조건문
  • break; 를 작성해 주지 않으면 switch 문 끝까지 실행
  • default 문은 생략 가능
  • if 조건문과 비교해보면 if는 조건식 결과에 true/false 만 가능하고 switch는 정수나 문자열만 가능
  • 실행 흐름
    1. 조건식 계산
    2. 조건식의 결과와 일치하는 case 문으로 이동
    3. 해당 case 문의 문장들을 수행
    4. break; 를 만나거나 switch 문이 끝나면 switch 문 전체를 빠져나감
  • switch 문의 제약조건
    • switch 문의 조건식 결과는 정수 또는 문자열 이어야함
    • case 문 값은 정수 상수, 문자열만 가능하며 중복되지 않아야함

ex)

class Main {
    public static void main(String[] args) {
        int month = 8;
        String monthString = "";
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            case 0: case 13:
                     System.out.println("이런식으로 case 문을 사용할 수 있습니다.");
                     break;
            case 15:
            default: monthString = "Invalid month";
        }
        System.out.println(monthString);
    }
}

3. FOR

for (초기화; 조건식; 증감식) {
ㅤㅤㅤ조건식의 결과가 참인 동안 반복적으로 실행하고자 하는 문장;
}

실행 순서
1. 초기화
2. 조건식
3. 조건식이 참일 경우 문장 수행
4. 증감식
5. 조건식이 거짓이 될 때까지 반복

ex)

class Main {
    public static void main(String[] args) {
        // 1번
        for (int i = 1; i <= 10; i = i * 2) {
            System.out.println("1번 i는 현재 " + (i) + "입니다.");
        }
        System.out.println();
        // 2번
        for (int i = 10; i >= 1; i--) {
            System.out.println("2번 i는 현재 " + (i) + "입니다.");
        }
    }
}

1. 중첩 for

for (초기화; 조건식1; 증감식) {
ㅤㅤㅤ조건식1의 결과가 참인 동안 반복적으로 실행하고자 하는 문장;
ㅤㅤㅤfor (초기화; 조건식2; 증감식) {
ㅤㅤㅤㅤㅤㅤ조건식2의 결과가 참인 동안 반복적으로 실행하고자 하는 문장;
ㅤㅤㅤ}
}

ex)

class Main {
    public static void main(String[] args) {
        for (int i = 2; i < 10; i++) {
            System.out.println(i + "단 시작합니다.");
            for (int j = 1; j < 10; j++) {
                System.out.println("j는 현재 " + (j) + "입니다.");
                System.out.println(i + "*" + j + "=" + (i * j));
            }
        }
    }
}

2. 향상된 for

for (타입 변수이름 : 배열 or 컬렉션) {
ㅤㅤㅤ배열 or 컬렉션의 길이만큼 반복적으로 실행하고자 하는 문장;
}

ex)

class Main {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 4, 5};

        for (int e : arr) {
            System.out.print(e + " ");
        }
    }
}

4. 임의의 정수 만들기

Math.random() -> 0.0과 1.0 사이의 임의의 double 값을 반환
0.0 <= Math.random() < 1.0

1 부터 5 사이의 random 한 정수 값 구하기
ㅤ1. 0.0 5 <= Math.random() 5 < 1.0 5
ㅤ2. (int)0.0 <= (int)(Math.random()
5) < (int)5.0
ㅤ3. 0 + 1 <= (int)(Math.random() 5) + 1 < 5 + 1
ㅤ4. 1 <= (int)(Math.random()
5) + 1 < 6

ex)

class Main {
    public static void main(String[] args) {
        // 괄호 { } 안의 내용을 20번 반복
        // 1. 1 ~ 10 사이의 난수를 20개 출력하시오.
        // 1,2,3,4,5,6,7,8,9,10

        // 2. -5 ~ 5 사이의 난수를 20개 출력하시오.
        // -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5
        for (int i = 0; i < 20; i++) {
            // 1번
            System.out.println(Math.random() * 10); // 1. 0.0 * 10 <= x * 10 < 1.0 * 10
            System.out.println((int)(Math.random() * 10)); // 2. 0 <= (int)(x * 10) < 10
            System.out.println((int)(Math.random() * 10) + 1); // 3. 1 <= (int)(x * 10) + 1 < 11

            // 2번
            System.out.println((int)(Math.random() * 11)); // 0 ~ 10
            System.out.println((int)(Math.random() * 11) - 5); // -5 ~ 5
        }
    }
}

5. WHILE

while (조건식) {
ㅤㅤㅤㅤ조건식의 결과가 참인 동안 반복적으로 실행하고자 하는 문장;
}

실행 순서
ㅤ1. 조건식
ㅤ2. 조건식이 참일 경우 문장 수행
ㅤ3. 조건식이 거짓이 될 때까지 반복

ex)

class Main {
    public static void main(String[] args) {
        int sum = 0;
        int i = 0;

        while (sum <= 100) {
            System.out.println("i = " + i);
            System.out.println("sum = " + sum);
            sum += ++i;
        }
    }
}

1. do - while

do {
ㅤㅤ조건식의 결과가 참인 동안 반복적으로 실행하고자 하는 문장;
} while (조건식);

실행 순서
ㅤ1. 처음 한 번은 무조건 실행
ㅤ2. 조건식
ㅤ3. 조건식이 참일 경우 문장 수행
ㅤ4. 조건식이 거짓이 될 때까지 반복

ex)

class Main {
    public static void main(String[] args) {
        int j = 1;

        do {
            System.out.println("do / while 문이 " + j + "번째 반복 실행중입니다.");
            j++; // 이 부분을 삭제하면 무한 루프에 빠지게 됨.
        } while (j < 20);

        System.out.println("do / while 문이 종료된 후 변수 j의 값은 " + j + "입니다.");
    }
}

6. break와 continue

1. break

  • 자신이 포함된 하나의 반복문을 벗어남

ex)

class Control6_1 {
    public static void main(String[] args) {
        int sum = 0;
        int i = 0;

        while (true) {
            if(sum > 100)
                break;
            ++i;
            sum += i;
        }

        System.out.println("i = " + i);
        System.out.println("sum = " + sum);
    }
}

2. continue

  • 자신이 포함된 반복문의 끝으로 이동
    • 그리고 다음 반복으로 넘어감
    • 전체 반복 중에서 특정 조건시 반복을 건너뛸 때 유용

ex)

class Control6_2 {
    public static void main(String[] args) {
        for (int i = 0; i <= 10; i++) {
            // 3의 배수는 건너뜀 : 3, 6, 9
            if (i % 3 == 0)
                continue;
            System.out.println("i = " + i);
        }
    }
}

3. 이름붙은 반복문

  • 반복문에 이름을 붙여서 하나 이상의 반복문을 벗어남

ex)

class Control6_4 {
    public static void main(String[] args) {
        int i = 2;
        allLoop :
        while (true) {
            for (int j = 1; j < 10; j++) {
                if (i == 5) {
                    break allLoop;
                }
                System.out.println(i + " * " + j + " = " + (i * j));
            }
            i++;
        }
    }
}

0개의 댓글