java_spring (2024.05 ~ 2024.10)
24.05.10
qordpsem
2024. 5. 10. 09:04
제어문 : 프로그램 수행 중에 사용자의 상황에 따라 흐름을 제어하는 명령어(문장)
- 선택문 : 상황에 따라 동작시켜야할 명령어 선택시키기 위한 문장 (if, switch)
- 반복문 : 조건을 만족할 동안 특정 명령어를 계속하여 반복 (for, while, do~while)
- 기타 : 제어문에서 사용하는 키워드 (break, continue)
for ( 초기값 ; 조건식 ; 증감식) {
반복시키고자 하는 명령어
}
while (조건식){
반복시키고자 하는 명령어들;
증감식;
}
초기값;
do{
}while
판별해야하는 case 가 여러가지일때 if ~ else if 를 사용할 수 있지만 문장구조가 복잡해진다
이럴때 switch case 를 사용하면 더 간결하게 표현할 수 있다
switch(항){
case 값1: 명령어1;
case 값2: 명령어2;
case 값3: 명령어3;
..
default: 명령어n;
}
예를 들면
import java.util.Scanner;
class D01DigiToKorIf {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
System.out.println("0~5 사이 수를 입력");
n = sc.nextInt();
if (n == 0){
System.out.println("영");
}else if(n == 1){
System.out.println("일");
}else if(n == 2){
System.out.println("이");
}else if(n == 3){
System.out.println("삼");
}else if(n == 4){
System.out.println("사");
}else if(n == 5){
System.out.println("오");
}else{
System.out.println("입력 범위를 넘었습니다");
}
}
}
import java.util.Scanner;
class D02Di {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
System.out.println("0~5 사이 수를 입력");
n = sc.nextInt();
switch (n){
case 0: //case와 0 사이 공백 필수
System.out.println("영");
break;
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;
default:System.out.println("입력 범위를 넘었습니다");
}
}
}
위 코드들은 동일한 기능을 한다 if 문인지 switch 문인지의 차이만 있다.
import java.util.Scanner;
class D05 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n;
System.out.println("0~5 사이 수를 입력");
n = sc.nextInt();
switch (n){
case 0:
case 1:System.out.println("일");break;
case 2:
case 3:
case 4:System.out.println("사");break;
case 5:System.out.println("오");break;
default:System.out.println("입력 범위를 넘었습니다");
}
}
}
이렇게 작성하면
0, 1을 입력할 경우 "일" 이 나오고, 2, 3, 4 를 입력할 경우 "사" 가 나온다.
import java.util.Scanner;
class D08Switch {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int month, lastDate = 31;
System.out.println("월을 입력하세요 ==> ");
month = sc.nextInt();
if (month < 1 || month > 12){
System.out.println("입력오류");
return;
}
switch (month){
case 4:
case 6:
case 9:
case 11:lastDate =30;break;
case 2:lastDate=28;break;
}
System.out.printf("%d월은 %d일까지 있어요", month, lastDate);
}
}
어제 if 문을 사용해서 작성한 월별 날짜 코드를 switch를 이용해서 작성해보았다.
#for 사용해서 코드 작성
//임의의 수 N 입력받아 1~N 중 홀수만 모두 출력
import java.util.Scanner;
class D14Test{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N;
System.out.println("숫자를 입력하세요 ==> ");
N = sc.nextInt();
for(int i=1; i<=N ; i=i+2){
System.out.println(i);
}
}
}