Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

4.3 switch 문 본문

이것이 자바다/04 조건문과 반복문

4.3 switch 문

빌드이너프 2024. 3. 29. 13:32

if문은 조건식의 결과가 true, false 두 가지밖에 없기 때문에 경우의 수가 많아질수록 else if를 반복적으로 추가해야 하므로 코드가 복잡함

switch 문은 변수의 값에 따라서 실행문이 결정되기 때문에 같은 기능의 if 문보다 코드가 간결해짐

 

switch 문의 괄호에는 정수 타입(byte, char, short, int, long)과 문자열 타입(String) 변수를 사용할 수 있다

 

예제

package ch04.sec03;

public class SwitchCharExample {
	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("손님");	
		}
	}

}
일반 회원