PART 03 조건문과 반복문

조재형·2023년 5월 4일
0

스터디

목록 보기
3/19

IF

if

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

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

if - else

if (조건식){
    조건식의 결과가 참일 때 실행하고자 하는 문장;
 }else{
    조건식의 결과가 거짓일 때 실행하고자 하는 문장;
 }
  • 예제코드
    class Control1_2 {
        public static void main(String[] args) {
            char ch = 'Z';
            if (ch >= 'a' && ch <= 'z') {
                System.out.println("해당 문자는 영문 소문자입니다.");
            } else {
                System.out.println("해당 문자는 영문 소문자가 아닙니다.");
            }
        }
    }

if - else if - else

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

  • else if 가 여러번 사용될 수 있음.

  • 마지막 else 블럭은 생략이 가능

    .
    .

  • 예제코드

      class Control1_3 {
        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등급입니다.");
        }
    }

    }

중첩 if

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

    class Control1_4 {
        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등급입니다.");
        }
    }

    }

블럭 {}

'여러 문장을 하나로 묶어주는 것'
만약 if 조건문에서 실행할 문장이 하나라면
if(조건식) 명령문; 이렇게 {} 가 생략될 수 있다

조건식의 다양한 예

조건식조건식이 참일 조건
90 <= x && x <= 100정수 x가 90이상 100 이하일 때
x < 0 ∥ x > 100정수 x가 0보다 작거나 100보다 클 때
x%3==0 && x%2!=0정수 x가 3의 배수이지만, 2의 배수는 아닐 때
ch=='y' ∥ ch=='Y'문자 ch가 'y' 또는 'Y'일 때
ch==' ' ∥ ch=='\t' ∥ ch=='\n'문자 ch가 공백이거나 탭 또는 개행 문자일 때
'A' <= ch && ch <= 'Z'문자 ch가 대문자일 때
'a' <= ch && ch <= 'z'문자 ch가 소문자일 때
'0' <= ch && ch <= '9'문자 ch가 숫자일 때
str.equals("yes")문자열 str의 내용이 "yes"일 때(대소문자 구분)
str.equalsIgnoreCase("yes")문자열 str의 내용이 "yes"일 때(대소문자 구분안함)

SWITCH

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 brak; 를 만나거나 switch 문이 끝나면 switch 문 전체를 빠져나간다

switch 문의 제약조건

1 switch 문의 조건식 결과는 정수 또는 문자열 이어야 한다
2 case 문의 값은 정수 상수(문자 포함), 문자열 만 가능하며, 중복되지 않아야 한다

int num, result;
final int ONe = 1;
switch (result) {
	case '1':	// OK. 문자 리터럴(정수 49와 동일)
    case ONE:	// OK. 정수 상수
    case "YES"	// OK. 문자열 리터럴
    case num:	// Error. 변수는 불가능
    case 1.0:	// Error. 실수도 불가능
}
  • 예제코드
    class Control2_1 {
        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);
        }
    }

FOR

for

for (초기화; 조건식; 증감식){
	조건식의 결과가 참인 동안 반복적으로 실행하고자 하는 문장;
}
실행 순서
1 초기화
2 조건식
3 조건식이 참일 경우 문장 수행
4 증감식
5 조건식이 거짓이 될 때 까지 반복
  • 예제코드
    class Control3_1 {
        public static void main(String[] args) {
            int i = 0;
            for (i = 0; i < 5; i++) {
                System.out.println("for 문이 " + (i + 1) + "번째 반복 실행중입니다.");
            }
            System.out.println("for 문이 종료된 후 변수 i의 값은 " + i + "입니다.");
        }
    }
  • 예제코드2
    class Control3_2 {
        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) + "입니다.");
            }
        }
    }
  • 예제코드3
    class Control3_3 {
        public static void main(String[] args) {
            // 초기화 시 변수 2개 사용 가능합니다. 단, 타입이 같아야 한다.
            for (int i = 1, j = 10; i <= 10; i++, j--) {
                System.out.println("i는 현재 " + (i) + "입니다.");
                System.out.println("j는 현재 " + (j) + "입니다.");
            }
            System.out.println();
            // 이렇게 변수 2개를 사용하여 조건식을 구성할 수 있습니다.
            for (int k = 1, t = 10; k <= 10 && t > 2; k++, t--) {
                System.out.println("k는 현재 " + (k) + "입니다.");
                System.out.println("t는 현재 " + (t) + "입니다.");
            }
        }
    }

중첩for

for(초기화; 조건식1; 증감식){
	조건식1의 결과가 참인 동안 반복적으로 실행하고자 하는 문장;
    for (초기화; 조건식2; 증감식){
    	조건식2의 결과가 참인 동안 반복적으로 실행하고자 하는 문장;
    }
}
  • 예제코드
    class Control3_4 {
        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));
                }
            }
        }
    }

향상된 for

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

    class Control3_5 {
        public static void main(String[] args) {
            int[] arr = new int[]{1, 2, 3, 4, 5};
        for (int e : arr) {
            System.out.print(e + " ");
        }
    }

    }

위 코드는 배열이므로 배열을 배우고 난 후에 학습하여도 좋음


임의의 정수 만들기

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

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
  • 예제코드
    class Control4_1 {
        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
            }
        }
    }

WHILE

while

while(조건식){
	조건식의 결과가 참인 동안 반복적으로 실행하고자 하는 문장;
}
실행 순서
1. 조건식
2. 조건식이 참일 경우 문장 수행
3. 조건식이 거짓이 될 때 까지 반복
  • 예제코드

    class Control5_1 {
        public static void main(String[] args) {
            int i = 10; // while 반복 횟수 , 즉 for 문의 초기화
    //        while (i-- != 0) {
    //            System.out.println(i);
    //        }
            // 위 코드와 같은 동작을 수행합니다.
            while (i != 0) {
                i--;
                System.out.println(i);
            }
        }
    }
  • 예제코드 2

    class Control5_2 {
        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;
    	    }
    	}
    }
  • 예제 2번의 결과

    i = 0
    sum = 0
    i = 1
    sum = 1
    i = 2
    sum = 3
    i = 3
    sum = 6
    i = 4
    sum = 10
    i = 5
    sum = 15
    i = 6
    sum = 21
    i = 7
    sum = 28
    i = 8
    sum = 36
    i = 9
    sum = 45
    i = 10
    sum = 55
    i = 11
    sum = 66
    i = 12
    sum = 78
    i = 13
    sum = 91


break 와 continue

break

자신이 포함된 하나의 반복문을 벗어난다

  • 예제코드

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

    결과

continue

자신이 포함된 반복문의 끝으로 이동

  • 그리고 다음 반복으로 넘어간다
  • 전체 반복 중에서 특정 조건시 반복을 건너뛸 때 유용함
  • 예제코드
    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);
            }
        }
    }

결과

이름붙은 반복문

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

  • 예제코드 1
    class Control6_3 {
        public static void main(String[] args) {
            allLoop :
            for (int i = 2; i < 10; i++) {
                for (int j = 1; j < 10; j++) {
                    if (i == 5) {
                        break allLoop;
                    }
                    System.out.println(i + " * " + j + " = " + (i * j));
                }
            }
        }
    }

결과

  • 예제코드 2
    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++;
            }
        }
    }

결과

  • 예제코드 3
    class Control6_5 {
        public static void main(String[] args) {
            allLoop : for (int i = 2; i < 10; i++) {
                for (int j = 1; j < 10; j++) {
                    if (i == 5) {
                        continue allLoop;
                    }
                    System.out.println(i + " * " + j + " = " + (i * j));
                }
            }
        }
    }

결과

세 예제 모두 결과는 같지만
코드 작성 방법이 다르다
참고하면 아주 도움이 될 것 같다

profile
안녕하세요.

0개의 댓글