멍발자의 개발
기본 문법 복습 (4) 본문
요즘 Switch문은 람다식을 관련해서 쓰는 경우가 많다.
인텔리제이를 이용하는 사람이라면 if문을 switch으로 바꾸기를 통하여 그 결과값을 확인할 수 있다.
<Switch문 예시>
public class SwitchSample {
public static void main(String[] args) {
var a = 5;
switch (a) {
case 1, 2 -> System.out.println("1, 2");
case 3 -> System.out.println("3");
case 4 -> System.out.println("4");
case 5 -> System.out.println("5");
}
}
}
//결과
5
만약 선언된 변수가 없을 경우를 대비하여 dafault값은 넣어주도록 하자.
public class SwitchSample {
public static void main(String[] args) {
var a = 6;
switch (a) {
case 1, 2 -> System.out.println("1, 2");
case 3 -> System.out.println("3");
case 4 -> System.out.println("4");
case 5 -> System.out.println("5");
default -> System.out.println("기타");
}
}
}
//결과
기타
** 주의할 점은 default 값은 가장 나중에 써야 오류나지 않는다.
<Switch식 예시>
삼항 연산자대신 사용 가능하다. default문은 필수가 아니다.
오래된 형식에는 yield문을 쓸 때가 있다.
System.out.println(switch (a) {
case 1, 2 -> "1, 2";
case 3 -> "3";
case 4 -> "4";
default -> "기타";
}
<데이터 구조> **중요
값을 정리해서 취급하는 구조다.
List = 동일한 자료형의 값을 처리한다.
ex. List.of
<배열>
구조 = new 형[요소수]
ex. var scores = new int[3]
'STUDY > Java' 카테고리의 다른 글
기초 문법 복습(6) (확장 for문, repeat문, 미로 게임) (0) | 2022.04.18 |
---|---|
기본 문법 복습 (5) 클래스 메소드 (0) | 2022.04.15 |
기본 문법 복습 (3) (0) | 2022.04.11 |
기초 문법 복습 (2) 별찍기 (0) | 2022.04.08 |
기본 문법 복습 (1) (0) | 2022.04.07 |
Comments