Notice
Recent Posts
Recent Comments
Link
관리 메뉴

데이터 과학

중첩 제어문 예제 본문

카테고리 없음

중첩 제어문 예제

티에스윤 2022. 9. 18. 21:38

중첩 제어문에 대한 예제입니다. 

 

public class IfPractice1 {
 public static void main (String args[]) {
    int num;
    String c;
    num = 1;
    if(num >= 0) 
     if(num!=0)
        System.out.println("positive");
    else
        System.out.println("negative");
   }
 }

 

 

결과
positive

 

 

public class IfPractice2 {
 public static void main (String args[]) {
    int num;
    String c;
    num = -1;
    if(num >= 0) 
     if(num!=0)
        System.out.println("positive");
    else
        System.out.println("negative");
   }
 }

 

 

결과

 

 

public class IfPractice3 {
 public static void main (String args[]) {
    int num;
    String c;
    num = 0;
    if(num >= 0) 
     if(num!=0)
        System.out.println("positive");
    else
        System.out.println("negative");
   }
 }

 

결과
negative

 

 

if 예제에서 블록을 만들어서 실행보면 좀 다른 결과가 나옵니다. 

 

 

public class IfPractice4 {
 public static void main (String args[]) {
    int num;
    String c;
    num = -1; {
    if(num >= 0) {
     if(num!=0)
        System.out.println("positive");
       }    else  {
        System.out.println("negative");
       }
    }
   }
 }

 

결과 

negative

 

결과가 negative가 나오는 이유는 if문의 블럭으로 else의 범위가 첫 번째 if문에 속해지기 때문입니다. 

 

 

for 중첩문

 

 

public class for1 {
 public static void main (String args[]) {
    int i, j;
        for (i = 1; i < 5; i++) {
            for(j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
       }
   }
 }

 

 

결과

*
**
***
****

 

 

아래 예제는 구구단 출력입니다. 

 

public class gugu {
 public static void main (String args[]) {
    int i, j;
        for (i = 2; i < 10; i++) {
            for(j = 1; j < 10; j++) {
                System.out.println(i + " * " + j + " = " + i*j);
            }
       }
   }
 }

 

 

public class star {
 public static void main (String args[]) {
    int i, j;
        for (i = 5; i>=1; i--) {
            for(j = 1; j <=i; j++) {
                System.out.print("*");
            }
            System.out.println("");
       }
   }
 }

 

결과 

*****
****
***
**
*

 

public class star2 {

public static void main (String args[]) {

   int i, j, k;

   for (i = 1; i<=4; i++) {

       for(j = 5-i; j >0; j--) {

          System.out.print(" ");

         }

        for (k = 1; k<=i*2-1; k++) {

          System.out.print("*");

        }

    System.out.println(" ");

   }

  }

}

 

 

출력

    * 
   *** 
  ***** 
 ******* 

 

 

for 중첩문으로 별을 여러 개 만들어 보고 구구단도 만들어 보았습니다.