문법
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | switch(조건식) { case 값1 : // 조건식의 결과가 값1과 같을 경우 수행될 문장 // ... break; case 값2 : // 조건식의 결과가 값2과 같을 경우 수행될 문장 // ... break; // ... default : // 조건식의 결과와 일치하는 case문이 없을 때 수행될 } | cs |
예제
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 | public class SwitchTest1 { public static void main(String[] args) { // math클래스의 random()함수 사용 int scr = (int)(Math.random() * 10) + 1; switch(scr*100) { case 100 : System.out.println("당신의 점수는 100점"); break; case 200 : System.out.println("당신의 점수는 200점"); break; case 300 : System.out.println("당신의 점수는 300점"); break; case 400 : System.out.println("당신의 점수는 400점"); break; default : System.out.println("점수미달~~~"); } } } | cs |
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 31 32 33 | public class SwitchTest2 { public static void main(String[] args) { int scr = (int)(Math.random() * 10) + 1; String msg =""; scr *= 100; msg = "당신의 점수는 " + scr + "점 "; switch(scr) { case 1000 : msg += "에어컨, "; break; case 900 : msg += "TV, "; break; case 800 : msg += "모니터, "; break; case 700 : msg += "스피커, "; break; default : msg += "마우스, "; } System.out.println(msg + "입니다."); } } | cs |