9월 3일 수업 정리 - switch

 조건문 : 삼항 연산자와 비슷하다. 


1) if문


2) switch 문 



if문

- if (조건식) {} 

괄호의 조건식의 결과가 true이면 블럭 {}안의 문장을 수행한다. 


-else if (조건식) {}

다수의 조건이 필요할때 if 뒤에 추가한다. 


-else{} 

결과가 true인 조건식이 하나도 없는 경우를 위해 추가한다. 

(마지막은 조건 외에 나머지인 경우에 수행 ) 


*병렬이 틀어졌다고 느낄때 깔끔하게 정리할때 맞추고 싶은 부위를 블럭지정한 뒤에 ctrl + shift + f 를 누르면 병렬을 할 수 있다. 



ex ) 


int a = 1;


if (a == 1) {

    System.out.println(" 조건식의 연산결과가 true 이면 수행된다. " ); 

}

if(a == 0 ) {

    System.out.println("조건식의 연산결과가 false 이면 수행되지 않는다.");


왜 여기는 다른데 왜 else if 를 사용하지 않았지?? : 내가 생각하는 차이 : if else if 는 만약 if에

만족하는 조건을 발견하면 그 다음에는 실행되지 않고 나아가는 거고 

만약에 if if 면 if 가 조건을 만족하지 않으면 그다음에 if 를 향해 나아가는 것 아닐까? 

}

if( a ==1) { 

    System.out.println("a가 1인 경우에 하고 싶은 것");


}else if ( a == 2) {

    System.out.println("a가 2인 경우에 하고 싶은것 " );


//else if는 위에 if 모두 해당이 안되면 가는 거겠네. 


}else if (a == 3){

    System.out.println("a가 3인 경우에 하고 싶은 것 " );

}else{

    System.out.println("이외에 경우에 하고 싶은것");


]

    


/ 위에서부터 조건문 실행이 되고 if가 실행되면 밑에 검사하지 않고 빠져나간다. 



과제 1. )  시험점수가 60점 이상이면 합격 그렇지 않으면 불합격


int score = 70; 


if (score >= 60 ){

    System.out.println("합격") ; 

}else

    System.out.println("불합격");

  



과제2.) 


성적에 등급을 부여하는 프로그램을 작성해 주세요


score = 100;


String grade = null ; 


if( 90 <= score && score <= 100 ){

    System.out.println(" 학점 : A " );


}else if ( 80 <= score && score < 90 ) {

    System.out.println("학점 : B " ) ; 

}else if ( 70 <= score && score < 80) {

    System.out.println("학점 : C " ) ; 

}else if ( 60 <= score && score < 70 ) { 

    System.out.println("학점 : D" ) ; 

}else { 

    System.out.println("학점 : F " ) ; 

}


요건 내가 한거고 이거를 간단하게 할 수 있어 

그러니까 if 아니면 else if로 이게 서로 배척되는 내용이라서 if가 만약에 완성이 되면 else if는 볼것도 없이 거짓이된다. 그래서 범위를 다 지정해줄필요없이 if라는 가정에서 정해진 범위는 제외하고 else if를 고려하기 때문에 



과제 

score = 100; 

String grade_ = null ; 

( 예시 String grade; 도 되는데 만약 else 가 없으면 문제가 생길 수 있다. ) 


if ( 90 <= score && score <=100) {

    grade_ = "A";


}else if ( 80 <= score) {

    grade_ = "B";

 

// 여기서 본 것처럼 그냥 80 < = score 이렇게만 써도 된다는말 if에서의 범위는 날라가니까


}else if(70 <= score) {

    grade_ = "c" ; 

}else { 

    grade_  = "F" ;


}


System.out.println(score + "점에 대한 등급은" + grade + " 입니다. " );


null 의미 : 값이 없다는 의미

아무것도 없는 값으로 초기화를 일단 해준것. 




3. 과제 ) 


score = 100;

grade = null; 


if ( 90 <= score && score <= 100) { 

    grade = "A" ; 

    if ( 97< = scrore ){

        grade += "+"

    }else if ( score <= 93) {

        grade += "-";

    }

}

else if(80 <= scrore) {

grade = "B";

    if(87 <= score ){

    grade += "+";  

    }else if ( 83 <= score){

    grade += "-"

}

}

else if ( 70 <= score) {

grade = "C"

    if(77 <= score ){

        grade += "+";

    }else if ( 73 >= score){

        grade += "-",

}

}

else if ( 60 <= score){

    grade = "D"

    if(68 <= score){

        grade += "+"

    if(63>= scores ) {

        grade += "-"

}

}





/ switch 문


- switch ( int / String) {case 1 : break;}


.break 를 만날 때까지 실행한다.

.조건식의 결과는 정수와 문자열만 허용한다 (jdk1.7부터 문자열 허용 ) 

.조건식과 일치하는 case 문 이후의 문장을 수행한다.



//과제 a 1, 2, 3 같은 일치하는 값


String b = "a"

switch(b){ 

case "a" 

System.out.println("b가 \"a\" 인 경우에 하고 싶은것 ");


\\역슬러시가 붙으면 기능을 바꿔준다 "를 문자열로 표현하고 싶을때 \" 문자열 안에 쌍따옴표를 넣어주는것 


case "b"

System.out.println("b가 \"b\"인 경우에 하고 싶은 것 " );

break;

default : 

System.out.println("b가 \"b\"인 경우에 하고 싶은 것 ");

break;


}



// 주어진 월에 해당하는 계절을 출력해 봅시다. 
   int month = 1;
   String season = null;
   switch(month){
   case 3:
   case 4:
   case 5:     
        season = "봄";
        break;
        
   case 6: case 7: case 8:
   season = "여름";
   break;
   
   case 9: case 10: case 11:
   season = "가을";
   break;
   default:
   season = "겨울";
   break;
   }
  System.out.println(month + "월은" + season + "입니다.");
  
  
  int score = 90;
  String grade = null;
  switch(score / 10 ){
  case 9 : case 10 : grade = "A"; break; 
  case 8: grade = "B"; break;
  case 7 : grade = "C"; break;
  case 6 : grade = "D"; break;
  default: grade = "F";
  
  }
  System.out.println(score + "점에 대한 등급은" + grade + "입니다.");
  
  
  //숫자를 입력받아 그 숫자가 0 인지 0이 아닌지 출력해 주세요. 

  
  Scanner sc = new Scanner(System.in);
     System.out.println("숫자를 입력하시오 : ");
     int x = Integer.parseInt(sc.nextLine());
     
     if(x == 0){
      System.out.println("0 입니다");
      
     }else { 
         System.out.println("0이 아닙니다");
     }
     
     
     //Switch 문을 사용 
     
     //switch 문은 정수밖에 못온다. 
     switch(x) {
     case 0 :
      System.out.println("0입니다.");
      break;
     default:
      System.out.println("0이 아닙니다.");
     }
      
     
  
     //숫자를 입력받아 그 숫자가 홀수인지 짝수인지 출력해주세요. 
     
    
     
     System.out.println("숫자를 입력해 주세요 : ");
     int skm = Integer.parseInt(sc.nextLine());
     
     if(skm % 2 == 0){
      System.out.println("짝수입니다.");
    }else {
     System.out.println ("홀수 입니다.");
  // }else if 는 갯수가 많을떄 사용한다. 
    
    
    
    }
    // switch 문으로. 
    
    
     //점수 3개를 입력받아 총점 , 평균, 등급을 출력해주세요. 
     System.out.println("첫번째 점수를 입력해주세요 : ");
        int s_ = Integer.parseInt(sc.nextLine());
        System.out.println("두번째 점수를 입력해 주세요: ");
        int j_ = Integer.parseInt(sc.nextLine());
        System.out.println("세번째 점수를 입력해 주세요 : ");
        int l_ = Integer.parseInt(sc.nextLine());
        
        int sum = s_ + j_ + l_;
        double avg = sum / 3.0;
        grade = null ;
        
        
        
        
       
       System.out.println( "합계 : " + sum ); 
       System.out.println( "평균 : " + sum );
       System.out.println( "등급 : " + sum ); 
        
        
        // 블럭지정한다음에 ctrl + f -> 찾기가 나옴. find 에 score를 찾아서 replace with 를 avg로 바꾼다 하면 전체 바꿔짐
        
        
        
        
        System.out.println("숫자 세개를 입력해 주세요");
       int num1 = Integer.parseInt(sc.nextLine());
       int num2 = Integer.parseInt(sc.nextLine());
       int num3 = Integer.parseInt(sc.nextLine());
       
       int sum1 = num1 + num2 + num3;
       
       double avr = sum1 / 3.0;
       
       if (avr >= 90 && avr <= 100){
        System.out.println("등급은 A입니다.");
       }else if ( avr >= 80 ){
        System.out.println("등급은 B 입니다.");
       }else if (avr >= 70){
        System.out.println("등급은 C 입니다.");         
       }else if (avr >= 60){
        System.out.println("등급은 D 입니다.");
       }else {
           System.out.println("등급은 F 입니다.");
       }
                   
    
        // 숫자 3개를 입력받아 오름차순으로 출력해주세요. 
       System.out.print("첫번째 숫자를 입력해 주세요>");
       int x_ = Integer.parseInt(sc.nextLine());
       
       System.out.print("두번째 숫자를 입력해 주세요>");
       int y = Integer.parseInt(sc.nextLine());
       
       System.out.print("세번째 숫자를 입력해 주세요>");
       int z = Integer.parseInt(sc.nextLine());
       
       
       
       if(x_ > y){
        int t = x_;
        x_ = y;
        y = t;
        
       }   if (x_ > z){
            int t1 = x_;
        
            x_ = z;
            z = t1;
        
       }  
    
           if ( y > z){
            int t = y;
            y = z;
            z = t;
        System.out.println(x + "," + y + "," + z); 
        
       }
       
       
       
       
   /*    System.out.println("서로 다른 숫자를 입력해 주세요:>");
       int a = Integer.parseInt(sc,nextLine());
       int b = Integer.parseInt(sc.nextLine());
       int c = Integer.parseInt(sc.nextLine());
       
       System.out.println(a,b,c);
    
       if ( a < b ){
               if (b < c){
                System.out.println(a + "," + b + "," + c);
               }
               else if (b > c){
                b = c;
                c = b;
                
                if ( a < c){
                System.out.println( a + "," + b + "," + c);
                }
                else if ( a > c){
                a = c;
                c = a;
                System.out.println ( a + "," + b + "," + c);
                }
               
                
               }
               }
       
        
       }else if (a > b){
     a = b;
     b = a;
         if (b < c){
             System.out.println(a + "," + b + "," + c);
        else
        b = c;
        c = b;
          System.out.println(a + "," + b + "," + c);
       }*/
    

댓글