23.05.01
- 개선된 switch-case문
public class NewSwitchCaseSeason {
public static void main(String[] args) {
int month = 11;
switch(month) {
case 12, 1, 2 -> System.out.println("겨울");
case 3, 4, 5 -> System.out.println("봄");
case 6, 7, 8 -> System.out.println("여름");
case 9, 10, 11 -> System.out.println("가을");
default -> System.out.println("해당하는 계절이 없습니다");
}
}
}
실행 결과
가을
- 표현식과 문의 차이
**표현식(expression)**은 값이나 변수, 연산자의 조합이며, 이 조합은 하나의 값으로 평가됩니다. 표현식은 어디서든 사용할 수 있으며, 값을 반환한다.
**문(statement)**은 프로그램의 실행 단위입니다. if문에서 if (조건식) {}, for문에서 for (초기화식;조건식;증감식) {}과 같이 문은 하나 이상의 표현식으로 구성되며, {} 중괄호 안쪽 영역이 실행될 것인지, 반복될 것인지와 같이 변수 선언, 값 할당, 제어 구조 등과 같은 작업을 수행한다.
- switch 표현식의 결과를 변수로
public class NewSwitchCaseDaysOfMonth {
public static void main(String[] args) {
int month = 11;
int lastDate = switch(month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> 28;
default -> throw new IllegalArgumentException("잘못된 월:" +
month);
};
System.out.println(lastDate);
}
}
실행 결과
30
- 반복문 for 문
- 반복문의 구조
public class NewSwitchCaseSeason {
public static void main(String[] args) {
int month = 11;
switch(month) {
case 12, 1, 2 -> System.out.println("겨울");
case 3, 4, 5 -> System.out.println("봄");
case 6, 7, 8 -> System.out.println("여름");
case 9, 10, 11 -> System.out.println("가을");
default -> System.out.println("해당하는 계절이 없습니다");
}
}
}
실행 결과
가을
- 표현식과 문의 차이
**표현식(expression)**은 값이나 변수, 연산자의 조합이며, 이 조합은 하나의 값으로 평가됩니다. 표현식은 어디서든 사용할 수 있으며, 값을 반환한다.
**문(statement)**은 프로그램의 실행 단위입니다. if문에서 if (조건식) {}, for문에서 for (초기화식;조건식;증감식) {}과 같이 문은 하나 이상의 표현식으로 구성되며, {} 중괄호 안쪽 영역이 실행될 것인지, 반복될 것인지와 같이 변수 선언, 값 할당, 제어 구조 등과 같은 작업을 수행한다.
- switch 표현식의 결과를 변수로
public class NewSwitchCaseDaysOfMonth {
public static void main(String[] args) {
int month = 11;
int lastDate = switch(month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> 28;
default -> throw new IllegalArgumentException("잘못된 월:" +
month);
};
System.out.println(lastDate);
}
}
실행 결과
30
- 반복문 for 문
- 반복문의 구조
예제)
public class ForLoopForward {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}
결과:
0~9까지 출
public class ForLoopPrintHorizontal {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.printf("%d", i);
}
}
}
결과 : 0123456789 한줄로 출력
public class ForLoopForward1To10 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
} 1부터 10까지 출력
public class ForLoopReverse {
public static void main(String[] args) {
// 5부터 역순으로 출력 54321
for (int i = 5; i > 0; i--) {
System.out.println(i);
}
}
}
public class ForLoopForwardStep {
public static void main(String[] args) {
//2씩 증가하기
for (int i = 0; i < 10; i+=2) {
System.out.println(i);
}
}
}