보통 statement는 위에서부터 아래로 실행된다. 하지만 제어문은 프로그램이 조건적으로 특정한 코드 블럭을 실행하도록하여 기존의 실행 흐름을 깬다. 제어문은 선택문, 반복문, 분기문으로 구성된다.
if문은 제어문의 가장 기본이다. 조건이 참일 때만 특정 부분의 코드를 실행시키도록 한다. 예를들어, Bycle이라는 클래스가 있다면, 자전거가 브레이크를 하여 속도를 줄이기 위해서는 자전거가 이미 움직이고 있는 상태여야만 한다.
void applyBreaks() {
// "if" 문 : 자전거는 반드시 움직이고 있어야한다
if(isMoving) {
// then
currentSpeed--;
}
}
void applyBreaks() {
if(isMoving)
currentSpeed--;
}
if문이 한 문장으로 구성된다면 다음과 같이 괄호를 쓰지 않아도 된다.
만약 조건이 일 경우, if문을 건너뛴다.
if-else문은 if절이 false일 때 또 다른 실행 경로를 제공한다. '자전거가 움직이지 않을 때' 새로운 행동을 할 수 있도록 한다.
void applyBreaks() {
if(isMoving) currentSpeed--;
else System.err.println("The bicycle has already stopped!");
}
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);
}
}
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들은 switch문들을 종료시킨다. break가 없다면 switch문에서 탈출할 수 없으므로 꼭 필요하다. break 만나면 그 지점에서 더 이상 statement를 시행하지 않고 빠져나온다.
반복문에서 continue를 만나면, "이후의 문장" 시행하지 않고, for(loop)문의 처음으로 돌아간다.
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
while (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 loop'이라고 언급하기도 한다.
for(initialization ; termination; increment) {
statement(s)
}
public class ForDemo {
public static void main(String[] args) {
for(int i=0; i<10; i++) System.out.println("Count is : " + i);
}
}
for( ; ; ) {
// code
}
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);
}
}