switch(변수 또는 계산식) {
case 값: 실행문; break;
case 값: 실행문; break;
case 값: 실행문; break;
default: 실행문; }
💻 1 "월요일", 2 "화요일",....7 "일요일"
int num=5; switch(num) { case 1:System.out.println("월요일");break; case 2:System.out.println("화요일");break; case 3:System.out.println("수요일");break; case 4:System.out.println("목요일");break; case 5:System.out.println("금요일");break; case 6:System.out.println("토요일");break; case 7:System.out.println("일요일");break; default: System.out.println("요일아님"); } // 금요일
💻 ch 'K' 이면 "KOREA"출력, 'U'이면 "USA"출력, 'C' 이면 "CANADA"출력, default 생략가능
char ch='K'; switch(ch) { case 'K':System.out.println("KOREA");break; case 'U':System.out.println("USA");break; case 'C':System.out.println("CANADA");break; } // KOREA
💻 medal "Gold" 금메달 출력, "Silver" 은메달 출력, "Bronze" 동메달 출력, 나머지 메달 없음
String medal="Gold"; switch (medal) { case "Gold":System.out.println("금메달");break; case "Silver":System.out.println("은메달");break; case "Bronze":System.out.println("동메달");break; default:System.out.println("메달없음"); }
for문 : 처음과 마지막을 알고 있으면 선택
예) 밥을 10번 드세요 -> 횟수가 정해짐 -> for
while문 : 처음과 마지막을 모를때, 반복 횟수가 정해져 있지 않은 반복문
예) 밥을 그릇이 빌 때까지 드세요 -> 횟수를 모름 -> while
※ 반복문 구성요소 -> 카운트 변수 초기값, 조건문, 실행문, 증가값
for(변수정의 초기값; 조건문; 증가값) {
실행문;
}
💻 1~10 반복하면서 1~10 출력
for(int i=1; i<=10 ;i++) {
System.out.println(i);
}
//i 변수는 for문 안에서 정의 -> for문 안에서만 사용가능
int min=1;
int max=10;
for(int i=min; i<=max; i++) {
System.out.println(i);
}
💻 1~5 반복하면서 "1~5 : Hello, world!" 출력
System.out.println("1 : Hello, world!");
System.out.println("2 : Hello, world!");
System.out.println("3 : Hello, world!");
System.out.println("4 : Hello, world!");
System.out.println("5 : Hello, world!");
i변수 조건문 실행문 증가값
1 1<=5 true 1:Hello 1 -> 2
2 2<=5 true 2:Hello 2 -> 3
3 3<=5 true 3:Hello 3 -> 4
4 4<=5 true 4:Hello 4 -> 5
5 5<=5 true 5:Hello 5 -> 6
6 6<=5 false -> 반복문 빠져나옴
💻 "1 3 5 7 9" 2씩 증가 출력
for(int i=1; i<10; i+=2) {
System.out.println(i);
}
💻 "10 9 8 7 ~ 2 1" 1씩 감소 출력
for(int i=10; i>=1 && i<=10; i--) {
System.out.println(i);
}
💻 구구단 2단 출력
System.out.println("<2단>");
System.out.println("2*1=2");
System.out.println("2*2=4");
System.out.println("2*3=6");
System.out.println("2*4=8");
System.out.println("2*5=10");
System.out.println("2*6=12");
System.out.println("2*7=14");
System.out.println("2*8=16");
System.out.println("2*9=18");
💻 구구단 30단 출력 (for문을 사용)
int dan=30;
for(int i=1; i<=9; i++) {
System.out.println(dan+"*"+i+ "="+i*dan);
}
초기값 s=0
i변수 조건문 s=s+i(i누적합)실행문 증가값
1 1<=5 true 0=0+1=>1 1 -> 2
2 2<=5 true 1=1+2=>3 2 -> 3
3 3<=5 true 3=3+3=>6 3 -> 4
4 4<=5 true 6=6+4=>10 4 -> 5
5 5<=5 true 10=10+5=>15 5 -> 6
6 6<=5 false -> 반복문 빠져나옴