본문 바로가기

Java 기본 문법 - 참조 서적 [이것이 자바다 - 한빛미디어]/2. 제어문

1. Java 자바 - 조건문 (if - else, switch)

 

 

조건문은 조건식의 결과에 따라 블록 실행 여부가 결정된다.

조건문에는 if, switch 문이 있다.

1. if문

 

형태

 


  if (조건식) {

      실행문;

      실행문;

      . . .

  }

  if (조건식)

      실행문;

 

실행문이 하나라면, 블록 기호 { } 를 생략할 수 있다.

 

조건식에는 true, false 값을 반환하는 연산식이나, boolean 변수가 올 수 있다.

 

true 이면 실행문을 실행하고, false 이면 실행하지 않는다.

 

 

 


2. if - else 문

 

else 블록과 함께 사용할 수 있다.

 

if 문의 조건식이 true 이면, if 블록 (실행문1) 이 실행되고, false 이면 else 블록(실행문2) 이 실행된다.

 


  if ( 조건식 ) {

    실행문1;

  } else {

     실행문2;

  }

 

- 연속된 if-else if-else 문

(여러 조건을 하나씩 모두 검사)

 

조건이 여러 개인 if문

else if 문 개수는 제한 없다.

여러 개의 조건 중 true 인 else if 블록만 실행하고 전체 if 문을 빠져나온다.

 

맨 마지막의 else 블록은 모든 조건식이 false 인 경우 실행되고 전체 if 문이 종료된다.

 


  if ( 조건식 ) {

      실행문1;

  } else if ( 조건식 ) {

      실행문2;

  } else if ( 조건식 ) {

      실행문3;

  } else {

      실행문4;

  }

 

public class IfElseIfElseExam {
    public static void main(String[] args) {
    	int score = 75;
        
        // 만족하는 조건 검사
        if (score >= 90) {
        	System.out.println("A");
        } else if (score >= 80) {
        	System.out.println("B");
        } else if (score >= 70) {
        	System.out.println("C");
        } else {
        	System.out.println("D");
        }
    }
}
            
           
        

 

 

 

더보기

주사위 굴려 나올 수 있는 1, 2, 3, 4, 5, 6 중 하나의 수를 뽑아 출력하는 프로그램

 

- Math.random( ) 메소드 이용 : 0.0 ~ 1.0 사이에 속하는 double 타입 난수 하나를 반환한다.

 

0.0 <= Math.random( ) < 1.0

 

원하는 범위의 정수를 임의로 얻기 위해서는

 

1. 각 변에 10을 곱한다.

 

0.0 * 10 <= Math.random( ) * 10 < 1.0 * 10

 

2. int 타입으로 강제 타입 변환 시킨다.

 

(int) 0.0 <= (int) (Math.random( ) * 10 < (int) 10.0

                                     (0)       (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)     (10)

 

3. 각 변에 1을 더하면 1 ~ 10 까지의 정수중 하나의 정수를 얻을 수 있다.

 

0 + 1 <= (int) ((Math.random( ) * 10) + 1 < 10 + 1

 

 

따라서 start 부터 n 개의 정수 중 임의의 정수 하나를 얻기 위해서는 아래와 같이 연산식을 쓴다.

 

int num = (int) (Math.random( ) * n) + start

 

주사위 1 ~ 6 범위의 정수 중 하나의 정수를 임의로 얻으려면

 

int num = (int) (Math.random( ) * 6) + 1;

 

public class DiceExam {
    public static void main(String[] args) {
    	int num = (int)(Math.random() * 6) + 1;  // 주사위 번호 하나 뽑기
        
        if (num == 1) {
        	System.out.println("1이 나왔습니다.");
        } else if (num == 2) {
        	System.out.println("2가 나왔습니다.");
        } else if (num == 3) {
        	System.out.println("3이 나왔습니다.");
        } else if (num == 4) {
        	System.out.println("4가 나왔습니다.");
        } else if (num == 5) {
        	System.out.println("5가 나왔습니다.");
        } else {
        	System.out.println("6이 나왔습니다.");
        }
    }
}      

 

 

 

- 중첩 if 문 

( if 문 블록 안에 다른 if 문 블록 또는 다른 제어문(if-else, while, do-while 등) 블록 넣을 수 있다.)

 

public class ScoreIfExam {
    public static void main(String[] args) {
    	int score = (int)(Math.random() * 20) + 81;   // 81 ~ 100 사이 뽑기
        System.out.println("점수 : " + score);
        
        String grade;
        
        if (score >= 90) {  // 90점보다 크거나 같고
        	if (score >= 95) {  //85 점보다 크면 (AND가 된다.)
            	grade = "A+";
            } else {
            	grade = "A";  //그냥 90점보다 크면
            }
        } else {  // 90점보다 작고
        	if (score >= 85) {  //85점 보다는 크거나 같으면
            	grade = "B+";
            } else {            // 85점 보다 작으면
            	grade = "B";
            }
        }
        
        System.out.println("학점 : " + grade);
    }
}
        
            

 

 

 


3. Switch 문

 

조건 변수가 어떤 값을 갖느냐에 따라 실행문이 선택되어 진다.

 

if - else 문은 조건식 결과가 true / false 밖에 없기 때문에 경우의 수가 많아질수록

if - else 반복적으로 추가해야 하는 번거로움이 있다.

 

형태

 

 
  switch (변수) {

    case 값1 : 

        실행문1;

        break;   // switch문 종료

    case 값2 :

        실행문2;

        break;  // switch문 종료

 

       .  .  .  .

   

    default :    // 만족하는 값이 없을 때    <default 부분은 생략 가능하다.>

        실행문D;

        break;

    }

 

 

위의 주사위 예제를 switch 문으로 바꾼 예제

 

public class SwitchDiceExam {
    public static void main(String[] args) {
    	int num = (int)(Math.random() * 6) + ;
        
        switch(num) {
        	case 1:
            	System.out.println("1이 나왔습니다.");
                break;
            case 2:
            	System.out.println("2가 나왔습니다.");
                break;
            case 3:
            	System.out.println("3이 나왔습니다.");
                break;
            case 4:
            	System.out.println("4가 나왔습니다.");
                break;
            case 5:
            	System.out.println("5가 나왔습니다.");
                break;
            default:
            	System.out.println("6이 나왔습니다.");
                break;
        }
    }
}        

 

만약 스위치 문을 빠져나가는 break; 문이 없다면, 다음 case가 case 값과 상관 없이 연달아서 실행된다.

 

다음 case에 break 문이 존재해야 switch 문을 빠져나갈 수 있다.

 

모든 case 가 break 문이 없다면, default 까지 모두 연달아서 수행된다.

 

public class NobreakSwitchExam {
    public static void main(String[] args) {
    	int time = (int)(Math.random() * 4) + 8;  // 8 ~ 11 사이 뽑기
        
        System.out.println("시간 : "+time+"시");
        
        switch(time) {
        	case 8:
            	System.out.println("출근합니다.");
            case 9:
            	System.out.println("회의합니다.");
            case 10:
            	System.out.println("업무를 봅니다.");
            default:
            	System.out.println("외근을 갑니다.");
        }
    }
}

 

9시라면, 회의, 업무, 외근 순으로 출력된다.

 

 

char 타입 변수도 switch 문에 사용될 수 있다.

 

예제 : 영어 대소문자 관계 없이 처리

 

public class CharSwitchExam {
    public static void main(String[] args) {
    	char grade = 'B';
        
        switch(grade) {
            case 'A':
            case 'a':
            	System.out.println("우수 회원입니다.");
                break;
            case 'B':
            case 'b':
            	System.out.println("일반 회원입니다.");
                break;
            default :
            	System.out.println("손님입니다.");
        }
    }
}            

 

 

String 타입도 switch 문에 사용될 수 있다. (자바 7 버전부터 가능)

 

public class StringSwitchExam {
    public static void main(String[] args) {
    	String position = "과장";
        
        switch(position) {
        	case "부장":
            	System.out.println("급여 : 700만원");
                break;
            case "과장":
            	System.out.println("급여 : 500만원");   //출력됨
                break;
            default:
            	System.out.println("급여 : 300만원");
         }
    }
}