switch
package sec04.chap02;
public class Ex01 {
public static void main(String[] args) {
int fingersOut = 2;
// ๐ก switch : ๊ดํธ ์์ ๊ธฐ์ค์ด ๋ ๋ณ์๋ฅผ ๋ฐ์
// ๊ฐ๋ฅํ ์๋ฃํ: byte, short, int, char, String, enum(์ดํ ๋ฐฐ์)
switch (fingersOut) {
// ๐ก case : ๊ธฐ์ค์ ์ผ์นํ๋ case๋ก ๋ฐ๋ก ์ด๋
// ๐ก break : switch๋ฌธ ์คํ์ ์ข
๋ฃ
// ๐ก default: ํด๋นํ๋ case๊ฐ ์์ ๋ - ๋ง์ง๋ง์ ์์ฑ
case 2:
System.out.println("๊ฐ์");
break;
case 0:
System.out.println("๋ฐ์");
break;
case 5:
System.out.println("๋ณด");
break;
default:
System.out.println("๋ฌดํจ");
}
}
}
package sec04.chap02;
public class Ex02 {
public static void main(String[] args) {
String direction = "north";
String dirKor;
// break ์ ๊ฑฐํ๊ณ ์คํํด ๋ณผ ๊ฒ
switch (direction) {
case "north":
dirKor = "๋ถ";
break;
case "south":
dirKor = "๋จ";
break;
case "east":
dirKor = "๋";
break;
case "west":
dirKor = "์";
break;
default:
dirKor = null;
}
System.out.println(
dirKor != null ? dirKor : "๋ฌดํจ"
);
}
}
package sec04.chap02;
public class Ex03 {
public static void main(String[] args) {
// ๐ก break ๊ด๋ จ ๋์๋ฐฉ์์ ์ด์ฉ
char yutnori = '๋';
switch (yutnori) {
case '๋ชจ': System.out.println("์์ผ๋ก");
case '์ท': System.out.println("์์ผ๋ก");
case '๊ฑธ': System.out.println("์์ผ๋ก");
case '๊ฐ': System.out.println("์์ผ๋ก");
case '๋': System.out.println("์์ผ๋ก"); break;
default:
System.out.println("๋ฌดํจ");
}
}
}
package sec04.chap02;
public class Ex04 {
public static void main(String[] args) {
byte month = 1;
byte season;
switch (month) {
case 1: case 2: case 3:
season = 1;
break;
case 4: case 5: case 6:
season = 2;
break;
case 7: case 8: case 9:
season = 3;
break;
case 10: case 11: case 12:
season = 4;
break;
default:
season = 0;
}
System.out.println(
season > 0
? "์ง๊ธ์ %d๋ถ๊ธฐ์
๋๋ค.".formatted(season)
: "๋ฌดํจํ ์์
๋๋ค."
);
}
}
package sec04.chap02;
public class Ex05 {
public static void main(String[] args) {
byte startMonth = 1;
String holidays = "";
switch (startMonth) {
case 1:
holidays += "์ค๋ , ";
case 2:
case 3:
holidays += "3ยท1์ , ";
break;
case 4:
case 5:
holidays += "์ด๋ฆฐ์ด๋ , ";
case 6:
holidays += "ํ์ถฉ์ผ, ";
break;
case 7:
case 8:
holidays += "๊ด๋ณต์ , ";
case 9:
holidays += "์ถ์, ";
break;
case 10:
holidays += "ํ๊ธ๋ , ";
case 11:
case 12:
holidays += "ํฌ๋ฆฌ์ค๋ง์ค, ";
break;
default:
holidays = null; // ํด์ผ์ด ์๋ ๋ถ๊ธฐ์ ๊ตฌ๋ถ
}
String result = holidays == null
? "(์๋ชป๋ ์์
๋๋ค)"
: "๋ถ๊ธฐ ๋ด ํด์ผ: " + holidays
.substring(0, holidays.lastIndexOf(", "));
}
}
Last updated