Back/JAVA
JAVA Step5 (스위치)
NOOWGNAJ
2022. 6. 6. 03:52
반응형
switch문
switch ~ case문 : 선택문
입력된 값 기준으로 case가 발동하여 출력값을 선택하게 된다.
default 는 case의 내용 중 같은 내용이 존재하지 않을 경우 작동되는 문법이다.
switch(인자값)
10개 이상 사용시 느려진다.
public class Switch {
public static void main(String[] args) {
int n = 3; // 옵션 case3 선택
switch(n) {
case 1:
System.out.println("옵션1을 선택하셨습니다.");
break;
case 2:
System.out.println("옵션2를 선택하셨습니다.");
break;
case 3:
System.out.println("옵션 3을 선택하셨습니다.");
break;
default:
System.out.println("선택한 값이 없습니다.");
break;
}
String user = "순신"; //문자로 switch문에 인자값 전달
switch(user) { // 복합 case형태.
case "이순신":
case "이 순신":
case "순신":
case "이순 신":
case " 순신":
case "Yeesunshin":
System.out.println("A조 입니다.");
break;
case "홍길동":
System.out.println("B조 입니다.");
break;
case "유관순":
System.out.println("C조 입니다.");
break;
default:
System.out.println("나머지는 D조 입니다.");
break;
}
}
}
[응용문제]
다음과 같은 질문을 받습니다.
"1번 ~ 5번 까지 숫자를 하나 입력해주세요"
출력
결과 내용
1 : 5 % 할인 쿠폰
2 : 10 % 할인 쿠폰
3 ~ 4 : 택배비 무료
5 : 다음기회에
import java.util.Scanner;
public class switch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("1번 ~ 5번 까지 숫자를 하나 입력해주세요.");
int inuser = sc.nextInt();
String msg = " ";
switch (inuser) {
case 1 :
msg = "5% 할인쿠폰";
break;
case 2 :
msg = "10% 할인쿠폰";
break;
case 3:
case 4:
msg = "택배비 무료";
break;
case 5:
msg = "다음기회에";
break;
}
System.out.println(msg);
sc.close();
}
}
위와 같은 결과로 14버전 이상의 자바에서 사용 가능한 코드.
import java.util.Scanner;
public class ver14upswitch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("1번 ~ 5번 까지 숫자를 하나 입력해주세요.");
int inuser = sc.nextInt();
String msg = " ";
switch (inuser) {
case 1 -> {
msg = "5% 할인 쿠폰";
}
case 2 -> {
msg = "10% 할인 쿠폰";
}
case 3,4 -> {
msg = "택배비무료";
}
case 5 -> {
msg = "다음 기회에...";
}
}
System.out.println(msg);
sc.close();
}
}
switch 반복문 사칙연산
import java.util.Scanner;
public class switchforao {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("1 부터 5 까지 계산할 사칙연산을 입력해주세요 + - * / ");
String inuser = sc.next();
int a;
int total=0;
switch (inuser) {
case "+" -> {
for(a = 1; a <= 5; a++) {
total += a;
}
}
case "-" -> {
for(a = 1; a <= 5; a++) {
total -= a;
}
}
case "*" -> {
total = 1;
for(a = 1; a <= 5; a++) {
total *= a;
}
}
case "/" -> {
total = 1;
for(a = 1; a <= 5; a++) {
total /= a;
}
}
}
System.out.printf("%s 로 계산된 값은 %d 입니다.", inuser, total);
}
}
반응형