ALGORITHM/문제해결

[JAVA] 홀수, 짝수 구별(oddNum, evenNum)

안낭우훗 2018. 8. 2. 01:10

/* 문제: 1 [홀수 짝수]
 * 0 ~ 9까지 숫자를 출력하고 각 숫자가 홀수인지 짝수인지 출력한다.
 * tip:  switch, if, ? :
 * 출력 예:
 * 0(짝수)
 * 1(홀수)

 

//  삼항연산자 사용

 

class Test{

  public static void main(String[] args) throws Exception {
    for(int i = 0; i <= 10; i++) {
      System.out.printf("%d : (%s) \n", i, (i % 2) == 0 ? "짝수" : "홀수") ;
    }
   }
}

 

//  if 조건문

class Test{

  public static void main(String[] args) throws Exception {
    for(int i = 0; i <= 10; i++) {
      if (i % 2 == 0) {
        Print(i, "짝수");
      } else if (i % 2 != 0) {
        Print(i, "홀수");
      } else {
        System.out.printf("응?");
      }
    }
   }
   static void Print(int no, String odd_even ) {
     System.out.printf("%d (%s) \n", no, odd_even);
   }
}

 

// switch case

class Test{

  public static void main(String[] args) throws Exception {
    for(int i = 0; i <= 10; i++) {

      switch (i % 2) {
        case 0 : Print(i, "짝수");
        break;
        case 1 : Print(i, "홀수");
        break;
        default :
        break;
      }
    }
   }
   static void Print(int no, String odd_even) {
     System.out.printf("%d (%s) \n", no, odd_even);
   }
}