JAVA 기초(5) 조건문

Dayon·2023년 11월 6일
0

자바-기초다지기

목록 보기
5/6
post-thumbnail

😆 1. 조건문의 개요


기본 제어 구조

  • 순차 구조

    • 순차적으로 코드가 실행되는 것
    • 시작 부터 종료까지 각 단계가 순서대로 실행되는 순차 구조
    • 가장 단순한 구조이자 가장 많이 사용되는 구조이다.
  • 선택 구조

    • 두 가지 중에서 선택한 쪽으로 코드가 실행되는 것
    • 조건이 있을 때 둘 중에서 선택하는 선택 구조로 실제 프로그램에서 많이 볼 수 있다
  • 반복 구조

    • 동일한 코드가 반복적으로 여러번 실행 되는 것

🦄 2. if 문


기본 if문

  • if (조건식)
  • 참일때는 어떤 작업을 수행하고 거짓일때는 아무것도 하지않는 가장 단순한 if문의 형식
    if (조건식) 
    		실행할 문장 ;
    • 예제
      public class Code5_1 {
          public static void main(String[] args) {
              int num = 99 ;
      
              if (num < 100)
                  System.out.println("100보다 작습니다.");
          }
      }
      // 100보다 작습니다. 

if~else 문

  • 조건이 참이면 문장 1을 실행하고, 조건이 거짓이면 문장2을 실행하는 경우
    if (조건식) {
    		실행할 문장1 ;
    } else {
    		실행할 문장2 ; 
    }
    • 예제
      public class Code5_2 {
          public static void main(String[] args) {
              int num = 200 ;
      
              if (num < 100) 
                  System.out.println("num is smaller than 100");
              else 
                  System.out.println("num is bigger than 100") ; 
          }
      }
      // num is bigger than 100
  • 조건이 참일 때 실행할 문장이 여러개이고, 거짓일때 실행할 문장도 여러개인 경우
    • 예제
      import java.util.Scanner; 
      
      public class Code5_3 {
          public static void main(String[] args) {
              Scanner s = new Scanner(System.in); 
              int num ;
      
              System.out.println("enter the number :");
              num = s.nextInt();
      
              if (num % 2 == 0) 
                  System.out.println("num is even number");
              else 
                  System.out.println("num is odd number") ; 
              
              s.close();
          }
      }

중첩 if 문

  • 조건을 검사하는 과정이 두번 이상있는 경우에 사용함
  • if문 안에 또 다른 if 문이 있는 것
if (조건식) {
		  if (조건식2) {
					실행할 문장1 ;
			} else {
					실행할 문장2 ; 
			}
} else {
		실행할 문장2 ; 
}
  • 예제
    import java.util.Scanner; 
    
    public class Code5_4 {
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in); 
            int score ;
    
            System.out.println("enter the score :");
            score = s.nextInt();
    
            if (score >= 90) 
                System.out.println("A");
            else 
                if (score >= 80) 
                    System.out.println("B");
                else
                    if (score >= 70) 
                        System.out.println("C");
                    else 
                        if (score >= 60) 
                            System.out.println("D");
                        else    
                            System.out.println("F");
            
            s.close();
        }
    }

else if 문

  • 중첩 if 문은 is~else문 안에 또 if~else문이 들어있어 복잡해보임
  • 그래서 중첩 if문을 사용할때는 중간에 else~if를 else if로 줄여서 사용함
  • 예제
    import java.util.Scanner; 
    
    public class Code5_4 {
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in); 
            int score ;
    
            System.out.println("enter the score :");
            score = s.nextInt();
    
            if (score >= 90) 
                System.out.println("A");
            else if (score >= 80) 
                System.out.println("B");
            else if (score >= 70) 
                System.out.println("C");
            else if (score >= 60) 
                System.out.println("D");
            else    
                System.out.println("F");
            
            s.close();
        }
    }
  • 전체 if문 예제
    import java.util.Scanner; 
    
    public class Code5_4 {
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in); 
            String myhand, comhand ; 
    
            System.out.print("my rock sis paper  =>");
            myhand = s.next() ; 
    
            String[] hands = { "rock", "sis", "paper"};
            int randno = (int)(Math.random() * hands.length);
            comhand = hands[randno];
            
            System.out.println("computer rock sis paper => " + comhand);
    
            if (myhand.equals("rock") ) {
                // System.out.println("hi1");
                if (comhand.equals("rock")){
                    System.out.println("both win");
                } else if (comhand.equals("paper")){
                    System.out.println("you lose");
                } else {
                    System.out.println("you win");
                }
            } else if(myhand.equals("paper") ){        
                System.out.println("hi2");    
                if (comhand.equals("paper")){
                    System.out.println("both win");
                } else if (comhand.equals("sis")){
                    System.out.println("you lose");
                } else {
                    System.out.println("you win");
                }
            } else {
                System.out.println("hi");
            }
    
            s.close(); 
        }
    }
        String[] hands = { "rock", "sis", "paper"};
        int randno = (int)(Math.random() * hands.length);
        comhand = hands[randno];

배열에서 랜덤값을 출력



🍺 3. switch ~ case 문


switch~case 문의 개요

  • 이중 분기와 다중 분기

  • 이중 분기 : 참 또는 거짓 중에서 하나를 선택한 조건문 → if문

  • 다중 분기 : 참 또는 거짓 만으로 해결할 수 없고, 여러개 중에서 하나를 선택해야 하는 조건문 (switch~case문)

swich(정수값) {
		case 정수값1 :
				실행할 문장 1 ; 
				break ; 
		case 정수값2 :
				실행할 문장 2 ; 
				break ; 
		default :
				실행할 문장 3 ; 
				break ; 
  • 예제
    import java.util.Scanner;
    
    public class Code05_19 {
        public static void main(String[] args){
            Scanner s = new Scanner(System.in);
            int select ; 
    
            System.out.println("1~3 choose the number : ");
            select = s.nextInt();
    
            switch(select) {
                case 1: 
                    System.out.println("you choose 1"); 
                    break;
                case 2:
                    System.out.println("you choose 2"); 
                    break;  
                case 3: 
                    System.out.println("you choose 3"); 
                    break;
                default : 
                    System.out.println("you choose strange number"); 
            }
    
            s.close();
        }
    }

break문을 사용하지 않을 경우 - switch~case문을 빠져나가지 못하고 다음 코드를 계속 수행한다.


profile
success is within reach, allow yourself time

0개의 댓글