티스토리 뷰

선택 제어문

어떤 조건인지에 따라 실행할 명령문을 선택

 

1. if문

if (조건식) {
    //참일 때 실행문
}

 

*실행문이 하나일 경우, 중괄호 생략 가능

if(3>5)
    System.out.println("Hello!");  //if 실행문. 거짓이라 출력 x
    System.out.println("Bye!");  //if문과 상관없는 실행문. 그러므로 출력.

 

실행문이 하나일 경우에만 해당하며 실행문이 2개 이상일 경우 반드시 중괄호(블록)로 감싸줘야 한다.

 

(1) type_1 : if

조건식을 만족하면 중괄호(블록) 안의 실행문을 실행하고 거짓일 경우 아무 것도 실행하지 않음.

Scanner sc = new Scanner(System.in);
System.out.println("점수를 입력하세요.");
int score = sc.nextInt();

if(score >= 70){
    System.out.println("합격입니다.");
    System.out.println("축하합니다.");
}
System.out.println("End"); //참, 거짓과 상관없이 if문 끝난 후 출력되는 문장

 

 

(2) type_2 : if - else

참 → if 실행문

거짓 → else 실행문

이것을 삼항연산자로 간단하게 표현할 수 있음.

Scanner sc2 = new Scanner(System.in);
System.out.println("점수를 입력하세요.");
int score2 = sc2.nextInt();
		
if(score2 >= 70) {
    System.out.println("PASS");
} else {
    System.out.println("FAILURE");
}

//삼항연산자
String result = (score2 >= 70) ? "PASS" : "FAILURE";
System.out.println(result);

_예제) 2과목 모두 70점 이상 맞아야 합격

Scanner sc = new Scanner(System.in);
System.out.println("Enter Scores");
int score1 = sc.nextInt();
int score2 = sc.nextInt();
		
//조건 : 합격
if(score1 >= 70 && score2 >=70) {
    System.out.println("PASS");
} else {
    System.out.println("FAILURE");
}
		
//조건 : 불합격
if(score1<70 || score2<70) {
    System.out.println("FAILURE");
}else {
    System.out.println("PASS");
}

 

(3) type_3 : if - else if - else

다중 if문

_예제) 입력받은 2개의 점수가 각각 70점 이상이어야 합격,

두 점수의 평균을 구하여 등급 출력(평균>=90이면 A, >=80이면 B, >=70이면 C)

Scanner sc = new Scanner(System.in);
System.out.println("시험 점수 2개를 입력하세요");
int score1 = sc.nextInt();
int score2 = sc.nextInt();
int avg = (score1+score2)/2;
		
if(score1 >= 70 && score2 >= 70) {
    System.out.println("축하합니다! 시험에 합격하셨습니다.");
    if(avg >= 90) {
        System.out.println("A");
    }else if(avg >= 80) {
        System.out.println("B");
    }else if(avg>=70) {
        System.out.println("C");
    }
}

2. switch - case

다중 if문을 간편하게

정수, 문자, 문자열만 변수로 가능. 범위, 조건식은 불가.

switch(점프위치변수){  //표현식 - 변수 가능
    case 위치값1 : 실행내용; break;
    case 위치값2 : 실행내용; break;
    ...
    case 위치값n : 실행내용; break;
    default : 실행내용;
}

└case값 : 정수, 문자, 문자열 가능. 실수 불가!

 

_예제) 입력받은 값에 따라 등급 출력

Scanner sc = new Scanner(System.in);
System.out.println("등급을 입력하세요.");
int rank = sc.nextInt();
		
switch(rank) {
case 1 : System.out.println("Gold"); break;
case 2 : System.out.println("Silver"); break;
case 3 : System.out.println("Bronze"); break;
default : System.out.println("No medal");  //마지막 문장은 break 쓸 필요 없음.
}

-break;가 있어야 해당하는 값만 출력함. rank == 1일 때 Gold만 출력.

 만약 break;가 없다면,

 rank == 1이어도 Gold, Silver, Bronze, No medal 전부 출력.

 

-'case n' : case와 n 쓸 때 띄워쓰기 안 하니까 오류남.

 

_다중 if문(type_3) → switch문 변환

평균 점수에 따라 등급 출력

Scanner sc2 = new Scanner(System.in);
System.out.println("평균 점수 입력");
int score = sc2.nextInt();

switch(score/10) {
case 10 :
case 9 : System.out.println("A"); break;
case 8 : System.out.println("B"); break;
case 7 : System.out.println("C"); break;
default : System.out.println("F");
}

└Point : 정수 나눗셈 이용. 99/10 →9, 90/10 → 9라는 점을 이용. (정수 / 정수) → 정수 반환

└Point : case 10과 case 9는 같은 결과이기 때문에 case 10의 출력문과 break; 생략.

   하나의 실행문에 break를 사용하지 않고 여러 개의 case를 연결하는 경우, 코드가 간결해질 수 있음.

 

_예제) case 실행문과 break 의도적 미사용

월별 마지막 날짜 출력

Scanner sc = new Scanner(System.in);
System.out.println("월을 입력하세요");
int month = sc.nextInt();
int day;
		
switch(month) {
case 1 : case 3 : case 5 : case 7 : case 8 : case 10 : case 12 :
    day = 31; break;
case 4 : case 6 : case 9 : case 11 :
    day = 30; break;
case 2 :
    day = 28; break;
default : day = 0;
}

System.out.println(month+"월은 마지막 날짜가 "+ day+"입니다.");

 

입력한 월의 계절을 출력

Scanner sc1 = new Scanner(System.in);
System.out.println("Enter Month");
int month1 = sc1.nextInt();
		
switch(month1) {
case 3 : case 4 : case 5 :
    System.out.println("Spring"); break;
case 6 : case 7 : case 8 :
    System.out.println("Summer"); break;
case 9 : case 10 : case 11 : 
    System.out.println("Fall"); break;
case 12 : case 1 : case 2 :
    System.out.println("Winter"); break;
default :
    System.out.println("잘못입력했습니다.");
}

 

입력받은 수와 수식에 따라 연산하는 조건문

Scanner sc2 = new Scanner(System.in);
System.out.println("2개의 숫자와 연산할 수식을 입력하세요.");
int num1 = sc2.nextInt();
int num2 = sc2.nextInt();
tring operator = sc2.next();
		
switch(operator){
case "+" : System.out.printf("%d + %d = %d", num1, num2, (num1+num2)); break;
case "-" : System.out.printf("%d - %d = %d", num1, num2, (num1-num2)); break;
case "*" : System.out.printf("%d * %d = %d", num1, num2, (num1*num2)); break;
case "/" : System.out.printf("%d / %d = %d", num1, num2, (num1/num2)); break;
default : System.out.println("연산자 입력 오류");
}

출력문을 이렇게 쓸 수도 있음. ↓ 값만 출력

switch(operator) {
case "+" : System.out.println(num1 + num2); break;
case "-" : System.out.println(num1 - num2); break;
case "*" : System.out.println(num1 * num2); break;
case "/" : System.out.println(num1 / num2); break;
default : System.out.println("연산자 입력 오류");
}

 

'수업 > └Java' 카테고리의 다른 글

[CH04_02]제어문 : 반복문  (0) 2022.01.30
[CH04_1]조건문 실습 예제_책  (0) 2022.01.30
[CH03]연산자  (0) 2022.01.30
[CH00]Scanner  (0) 2022.01.30
[CH02]변수와 자료형  (0) 2022.01.30
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함