조건문은 조건식과 문장을 포함하는 블럭{}으로 구성되어 있으며, 조건식의 연산결과에 따라 실행할 문장이 달라져서 프로그램의 실행흐름을 변경할 수 있다
조건문은 if문과 switch문, 두 가지가 있다
if문은 가장 기본적인 조건문이며, 다음과 같이 '조건식'과 '괄호{}'로 이루어져 있다
if(조건식){
//조건식이 참(true)일 때 수행될 문장들을 적는다
}
괄호{}를 이용해서 여러 문장을 하나의 단위로 묶을 수 있는데, 이것을 '블럭(block)'이라고 한다
블럭 내의 문장들은 탭(tab)으로 들여쓰기(indentation)를 해서 블럭 안에 속한 문장리나는 것을 알기 쉽게 해주는 것이 좋다.
if(score>60){
System.out.println("합격입니다.");
}
import java.util.*;
public class FlowEx2 {
public static void main(String[] args){
int input;
System.out.print("숫자를 하나 입력하세요.>");
Scanner scanner = new Scanner(System.in);
String tmp= scanner.nextLine();
input= Integer.parseInt(tmp);
if(input==0){
System.out.println("입력하신 숫자는 0입니다");
}
if(input!=0){
System.out.printf("입력하신 숫자는 %d입니다",input);
}
}
}
scanner을 통해 입력받은 값을 비교하는 예제이다
'else'의 뜻이 '그 밖의 다른'이므로 조건식의 결과가 참이 아닐 때, 즉 거짓일 때 else블럭의 문장을 수행하라는 뜻이다
if(조건식){
//조건식이 참(true)일 때 수행될 문장들을 적는다
}else{
//조건식이 거짓(false)일 때 수행될 문장들을 적는다
}
import java.util.Scanner;
public class FlowEx3 {
public static void main(String[] args){
System.out.print("숫자를 하나 입력하세요.>");
Scanner scanner = new Scanner(System.in);
String tmp= scanner.nextLine();
int input= Integer.parseInt(tmp);
if(input==0){
System.out.println("입력하신 숫자는 0입니다");
}else{
System.out.printf("입력하신 숫자는 %d입니다",input);
}
}
}
위의 예제를 if-else문으로 고친 결과이다
처리해야할 경우의 수가 셋 이상인 경우에 한 문장에 여러 개의 조건식으 쓸 수 있는 'if-else if'문을 사용하면 된다
if(조건식1){
//조건식1의 연산결과가 참일 때 수행될 문장들을 적는다
}else if(조건식2){
//조건식2의 연산결과가 참일 때 수행될 문장들을 적는다
}else if(조건식3){
//조건식3의 연산결과가 참일 때 수행될 문장들을 적는다
}else{
//위의 어느 조건식도 만족하지 않을 때 수행될 문장들을 적는다
}
import java.util.*;
public class FlowEx4 {
public static void main(String[] args){
int score=0;
char grade=' ';
System.out.print("점수를 입력하세요.>");
Scanner scanner=new Scanner(System.in);
score = scanner.nextInt();
if(score>=90){
grade='A';
}else if(score>=80){
grade='B';
}else if(score>=70){
grade='C';
}else{
grade='D';
}
System.out.println("당신의 학점은 "+grade+"입니다.");
}
}
score>=80&&score<90이 아닌 이유는 score>=90에서 전부 걸러지기 때문이다
if문의 블럭 내에 또 다른 if문을 포함시키는 것이 가능한데 이것을 중첩 if문이라고 부르며 중첩의 횟수에는 거의 제한이 없다
if(조건식1){
//조건식1의 연산결과가 true일 때 수행될 문장들을 적는다
if(조건식2){
//조건식1과 조건식2가 모두 true일 때 수행될 문장들
}else{
//조건식1이 true이고, 조건식2가 false일 때 수행되는 문장들
}
}else{
//조건1이 false일 때 수행되는 문장들
}
switch문은 단 하나의 조건식으로 많은 경우의 수를 처리할 수 있고, 표현도 간결하므로 알아보기 쉽다
처리할 경우가 많은 경우에는 if문 보다 switch문으로 작성하는 것이 좋다
1.조건식을 계산한다
2.조건식의 결과와 일치하는 case문으로 이동한다
3.이후의 문장들을 수행한다
4.break문이라 switch문의 끝을 만나면 switch문 전체를 빠져나간다
switch(조건식){
case 값1 :
//
//
break;
case 값2 :
//
//
break;
default:
//
//
만일 조건식의 결과와 일치하는 case문이 하나도 없는 경우에는 default문으로 이동한다
swtich문의 제약조건
1. switch문의 조건식 결과는 정수 또는 문자열이어야 한다
2. case문의 값은 정수 상수만 가능하며, 중복되지 않아야 한다
import java.util.*;
public class FlowEx6 {
public static void main(String[] args){
System.out.print("현재 월을 입력하세요.>");
Scanner scanner=new Scanner(System.in);
int month= scanner.nextInt();
switch (month){
case 3:
case 4:
case 5:
System.out.println("봄 입니다");
break;
case 6: case 7: case 8:
System.out.println("여름 입니다");
break;
case 9: case 10: case 11:
System.out.println("가을 입니다");
break;
default:
case 12: case 1: case 2:
System.out.println("겨울입니다");
break;
}
}
}
case문은 한 줄에 하나씩 쓰던, 한 줄에 붙여서 쓰던 상관없다
반복문은 어떤 작업이 반복적으로 수행되도록 할 때 사용되며, 반복문의 종류로는 for문과 while문, 그리고 while문의 변형인 do-whule문이 있다
for문이나 while문에 속한 문장은 조건에 따라 한 번도 수행되지 않을 수 있지만 do-while문에 속한 문장은 무조건 최소한 한 번은 수행될 것이 보장된다
for문은 반복 횟수를 알고 있을 때 적합하다
for(int i=1;i<=5;i++){
System.out.println("Hello java");
}
for(초기화;조건식;증감식){
//조건이 참일 때 수행될 문장들을 적는다
}
조건식이 참인 동안 블럭{} 내의 문장들을 반복하다 거짓이 되면 반복문을 벗어난다
반복문에 사용될 변수를 초기화하는 부분이며 처음에 한번만 수행된다
보통 변수 하나로 for문을 제어하지만, 둘 이상의 변수가 필요할 때는 아래와 같이 콤마','를 구분자로 변수를 초기화하면 된다
for(int i=1;i<=10;i++){...}//변수 i의 값을 1로 초기화 한다
for(int i=1,j=0;i<=10;i++){...}//int타입의 변수 i와 j를 선언하고 초기화
조건식의 값이 참(true)이면 반복을 계속하고, 거짓(false)이면 반복을 중단하고 for문을 벗어난다.
for(int i=1;i<=10;i++){ ... }//'i<=10'가 참인 동안 블럭 {}안의 문장들을 반복
반복문을 제어하는 변수의 값을 증가 또는 감소시키는 식이다
for(int i=1;i<=5;i++){...}
for(int i=1;i>=0;i--){...}
for(int i=1;i<=10;i+=2){...}
for(int i=1;i<=10;i*=3){...}
public class FlowEx12 {
public static void main(String[] args){
for(int i=1;i<=5;i++){
System.out.println(i);
}
for(int i=1;i<=5;i++){
System.out.print(i);
}
}
}
1부터 5까지 세로로 한번, 가로로 한번 출력하는 간단한 예제이다
public class FlowEx14 {
public static void main(String[] args){
for(int i=1,j=10;i<=10;i++,j--){
System.out.printf("%d \t %d%n",i,j);
}
}
}
for문에 i와 j, 두 개의 변수를 사용해서 i는 1부터 10까지 증가시키는 동시에, j는 10부터 1까지 감소시키면서 출력한다
public class FlowEx18 {
public static void main(String[] args){
for(int i=2;i<=9;i++){
for(int j=1;j<=9;j++){
System.out.printf("%d * %d = %d %n",i,j,i*j);
}
}
}
}
구구단을 출력하는 예제이다
for(타입 변수명 : 배열 또는 컬렉션){
//반복할 문장
}
public class FlowEx22 {
public static void main(String[] args){
int[] arr={10,20,30,40,50};
int sum=0;
for(int i=0;i<arr.length;i++) {
System.out.printf("%d ", arr[i]);
System.out.println();
}
for(int tmp:arr){
System.out.printf("%d ",tmp);
sum+=tmp;
}
System.out.println();
System.out.println("sum="+sum);
}
}
향상된 for문은 일반적인 for문과 달리 배열이나 컬렉션에 저장된요소들을 읽어오는 용도로만 사용할 수 있다는 제약이 있다
조건식이 거짓이 될 때까지 블럭{} 내의 문장을 반복한다
while(조건식){
//조건식의 연산결과가 참(true)인 동안, 반복될 문장들을 적는다
}
public class FlowEx23 {
public static void main(String[] args){
int i=5;
while(i--!=0){
System.out.println(i);
}
}
}
변수 i의 값만큼 블럭{}을 반복하는 예제이다
do-while문은 while문의 변형으로 기본적인 구조는 while문과 같으나 조건식과 블럭{}의 순서를 바꿔놓은 것이다
while문과 반대로 블럭{}을 먼저 수행한 후에 조건식을 평가한다
do{
//조건식의 연산결과가 참일 때 수행될 문장들을 적는다
}while(조건식);
import java.util.*;
public class FlowEx28 {
public static void main(String[] args){
int input=0, answer=0;
answer=(int)(Math.random()*100)+1;
Scanner scanner=new Scanner(System.in);
do{
System.out.print("1과 100사이의 정수를 입력하세요.>");
input = scanner.nextInt();
if(input>answer){
System.out.println("더 작은 수로 다시 시도해보세요");
}else if(input<answer){
System.out.println("더 큰 수로 다시 시도해보세요.");
}
}while(input!=answer);
System.out.println("정답입니다.");
}
}
Math.random()을 이용해서 1과 100사이의 임의의 수를 변수 answer에 저장하고, 이 값을 맞출 때까지 반복하는 예제이다.
반복문에서도 break문을 사용할 수 있는데, switch문에서 그랬던 것처럼, break문은 자신의 포함된 가장 가까운 반복문을 벗어난다
public class FlowEx30 {
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);
}
}
숫자를 1부터 계속 더해 나가서 몇까지 더하면 합이 100을 넘는지 알아내는 예제이다
continue문은 반복문 내에서만 사용도리 수 있으며, 반복이 진행되는 도중에 continue문을 만나면 반복문의 끝으로 이동하여 다음 반복으로 넘어간다
public class FlowEx31 {
public static void main(String[] args){
for(int i=0;i<=10;i++){
if(i%3==0){
continue;
}
System.out.println(i);
}
}
}
3의 배수인 것은 제외하고 1과 10사이의 숫자를 출력하는 예제이다