제어문

seul·2020년 12월 11일
0

4주차

제어문

보통 statement는 위에서부터 아래로 실행된다. 하지만 제어문은 프로그램이 조건적으로 특정한 코드 블럭을 실행하도록하여 기존의 실행 흐름을 깬다. 제어문은 선택문, 반복문, 분기문으로 구성된다.

선택문

if문

if문은 제어문의 가장 기본이다. 조건이 일 때만 특정 부분의 코드를 실행시키도록 한다. 예를들어, Bycle이라는 클래스가 있다면, 자전거가 브레이크를 하여 속도를 줄이기 위해서는 자전거가 이미 움직이고 있는 상태여야만 한다.

void applyBreaks() {
	// "if" 문 : 자전거는 반드시 움직이고 있어야한다
	if(isMoving) {
		// then 
		currentSpeed--;
		}
	}
void applyBreaks() {
	if(isMoving) 
		currentSpeed--;
	}

if문이 한 문장으로 구성된다면 다음과 같이 괄호를 쓰지 않아도 된다.

만약 조건이 일 경우, if문을 건너뛴다.

if-else문

if-else문은 if절이 false일 때 또 다른 실행 경로를 제공한다. '자전거가 움직이지 않을 때' 새로운 행동을 할 수 있도록 한다.

void applyBreaks() {
	if(isMoving) currentSpeed--;
	else System.err.println("The bicycle has already stopped!");
}
  • if-else 활용 예제
public class IfElseDemo {
    public static void main(String[] args) {
        int testScore;
        Scanner in = new Scanner(System.in);
        testScore = in.nextInt();
        char grade;
        if(testScore >= 90) grade = 'A';
        else if(testScore >= 80) grade = 'B';
        else if(testScore >= 70) grade = 'C';
        else if(testScore >= 60) grade = 'D';
        else grade = 'F';

        System.out.println("Grade = " + grade);
    }
}

switch문

if, if-else문과 다르게, switch문은 다수의 실행 경로를 가질 수 있다. switch문은 프리미티브 타입 중 byte, short, char, int으로 작업할 수 있다. 또한 enum type과 String 클래스, 그리고 Character, Byte, Short, Integer과 같이 확실한 프리미티브 타입으로 쌓인 소수의 특별한 클래스로도 작동한다.

public class SwitchDemo {
    public static void main(String[] args) {
        int month;
        Scanner in = new Scanner(System.in);
        month = in.nextInt();
        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;
            default: monthString = "Invalid month";
                break;
        }
        System.out.println(monthString);
    }
}

위의 코드는

int month;
month = in.nextInt();
if (month == 1) System.out.println("January");
else if (month == 2) System.out.println("February");

와 같은 if-else문으로 변경될 수 있다.

if-else문을 사용할지, switch문을 사용할지 어떻게 결정할까?

가독성과 테스트 하는 문장의 표현에 기초해서 결정하면 된다. if-else문은 값이나 조건의 범위에 따라 표현되는 반면 switch문은 오직 단수의 정수, 열거, 문자열로만 가능하다.

  • break

각각의 break들은 switch문들을 종료시킨다. break가 없다면 switch문에서 탈출할 수 없으므로 꼭 필요하다. break 만나면 그 지점에서 더 이상 statement를 시행하지 않고 빠져나온다.

  • continue

반복문에서 continue를 만나면, "이후의 문장" 시행하지 않고, for(loop)문의 처음으로 돌아간다.

  • case 여러 개 지정하는 방법
public class SwitchDemo2 {
    public static void main(String[] args) {
        int month;
        Scanner in = new Scanner(System.in);
        month = in.nextInt();
        int year;
        year = in.nextInt();
        int numDays = 0;
        
        switch (month) {
            case 1: case 3: case 5:
            case 7: case 8: case 10:
            case 12:
                numDays = 31;
                break;
            case 2 :
                if((year % 4 == 0) && ! (year % 100 == 0) || (year % 400 == 0))
                    numDays = 29;
                else numDays = 28;
            default:
                System.out.println("Invalid month.");
                break;
        }
    }
}

반복문

while과 do-while문

while

while (expression) {
	statement(s)
}
  • while문은 특정 조건이 참일 때 statement를 계속 실행한다.
  • while문은 반드시 boolean 값을 가지는 expression을 평가한다.
    • expression이 참일 때, 거짓이 될 때 까지 statement(s)를 실행

do-while

do {
	statement(s)
} while (expression);

while과 do-while의 차이점은 do-while은 expression이 loop의 처음에 위치한 것이 아닌 아래에 위치해있다는 것이다. 따라서 do 블록에 있는 statement는 항상 최소 한 번은 실행된다.

example

public class DoWhileDemo {
    public static void main(String[] args) {
        int count = 1;
        do {
            System.out.println("Count is : " + count);
            count++;
        } while (count < 11);
    }
}

for

for문은 값들의 범위를 반복하는 간단한 방법을 제공한다. 프로그래머들은 for문이 특정 조건을 만족할 때 까지 반복적으로 실행되기 때문에 'for loop'이라고 언급하기도 한다.

for(initialization ; termination; increment) {
	statement(s)
}
  • Initialization는 루프를 초기화하는 것이다. 루프가 시작할 때 딱 한 번 실행된다.
  • termination이 false가 될 때, 루프는 끝난다.
  • Increment는 루프가 끝난 뒤 발생한다. decrement도 가능
public class ForDemo {
    public static void main(String[] args) {
        for(int i=0; i<10; i++) System.out.println("Count is : " + i);
    }
}
  • 무한 루프
for( ; ; ) {
	// code 
}
  • 확장된 for 문 - 배열을 처리하는 루프를 보다 간결하고 읽기 쉽게 만드는 데 사용할 수 있다.
public class EnhancedForDemo {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int item : numbers) System.out.println("Count is " + item);
    }
}

출처

profile
무한삽질로그

0개의 댓글