19일차 Loop

4.8 for문

1.초기값 ; 2.조건; 4.증감; {3.실행}
1.초기값부터 시작해서 2.조건확인후 3.실행 4.증감 5.반복

public class C01For {
    public static void main(String[] args) {
        System.out.println("이전 코드...");

        for (int i = 0; i < 3; i++) {
            System.out.println("반복할 코드1");
            System.out.println("반복할 코드2");
        }

        System.out.println("실행 이어감..");
    }
}

4.8.1 whlie문과 for문의 차이

i라는 변수를 이전, 안에 선언하는 차이가 있다.
변수의 scope가 차이가 있다.

public class C02For {
    public static void main(String[] args) {
        // 변수의 scope
        int i = 0;
        while (i<3) {
            System.out.println("while loop");
            i++;
        }

        for (int j = 0; j < 3; j++) {
            System.out.println("for loop");
        }
    }
}

while의 i변수는 main전체의 변수이다.
for문도 초기화문을 밖에 두면 변수를 여러가지 방법으로 응용할 수 있다.

public class SumFrom1To100Example {
    public static void main(String[] args) {
        int sum = 0;
        int i;

        for (i = 1; i <=100 ; i++) {
            sum += i;
        }
        System.out.println("1~" + (i-1) + " 합: " + sum);
    }
}

4.8.2 확인문제

1~100까지의 3의배수 총합

public class ex3_2 {
    public static void main(String[] args) {
        // 1~ 100 까지 3의 배수의 총합
        int sum = 0;

        for (int i = 1; i <= 100; i++) {
            if (i % 3 == 0) {
                sum += i;
            }
        }
        System.out.println(sum); //1683
    }
}

4.8.3 여러 변수

for문을 사용할때 초기화변수를 여러개 작성할 수 있다. 생략해도된다.
증감식도 여러개 작성할 수 있다.

public class C03For {
    public static void main(String[] args) {
        for (int i = 0, j =10; i < 5; i++, j--) {
            System.out.printf("%d, %d\n", i, j);
        }
    }
}

4.8.4 실수 타입

for문을 작성할 때 주의할점은 부동 소수점을 쓰는 float타입을 사용하지 말아야한다.
부동소수점 방식의 float는 연산과정에서 정확히 0.1을 표현하지 못하기 때문에 증감식에서 x에 더해지는 실제값은 0.1보다 약간클 수 있다.
그래서 10번반복이 아닌 9번밖에 반복하지 못했다.

public class FloatCounterExample {
    public static void main(String[] args) {
        for (float x = 0.1f; x <= 1.0f ; x +=0.1f) {
            System.out.println(x);
        //0.1 0.2 0.3 0.4 0.5 0.6 0.70000005 0.8000001 0.9000001
        }
    }
}

4.8.5 중첩된 for문

헷갈리니 디버깅을 통해 순서대로 봐보자.

for (int i = 2; i <= 9; i++) {
    System.out.println(i + " 단");
    for (int j = 1 ; j <= 9; j++) {
        System.out.println(i + " * " + j + " = " + i*j);
    }

}

4.8.6 확인문제 5번

4x + 5y = 60 의 모든 해를 구해서 x,y로 출력하는 코드

public class ex5 {
    public static void main(String[] args) {
        for (int x = 1; x <= 10; x++) {
            for (int y = 1; y <= 10; y++) {
                if ((4 * x) + (5 * y) == 60) {
                    System.out.printf("(%d, %d)\n", x, y);
                }
            }
        }
    }
}

4.9 break문

반복문에서 break를 만나게되면 밑의 코드는 실행되지 않고 다음 실행흐름을 이어가게 된다.

public class C01Break {
    public static void main(String[] args) {
        while (true) {
            System.out.println("코드 반복1");
            System.out.println("코드 반복2");

            if (true) {
                break;
            }
            System.out.println("코드 반복3"); //Deadcode
            System.out.println("코드 반복4"); //Deadcode
        }
        System.out.println("다음 실행 코드들..");
    }
}

4.9.1 확인문제 4번

주사위두개던져서 합이 5면 반복문 종료시키기

public class ex4_2 {
    public static void main(String[] args) {
        int dice1;
        int dice2;

        while (true) {
            dice1 = ((int) (Math.random() * 6)) + 1;
            dice2 = ((int) (Math.random() * 6)) + 1;
            System.out.printf("%d, %d\n", dice1, dice2);

            if (dice1 + dice2 == 5) {
                break;
            }
        }
    }
}

4.9.2 라벨 break;

public class ex5_2 {
    public static void main(String[] args) {
        outerLoop: for (int x = 1; x <= 10; x++) {
            for (int y = 1; y <= 10; y++) {
                if ((4 * x) + (5 * y) == 60) {
                    System.out.printf("(%d, %d)\n", x, y);
                    break outerLoop;
                }
            }
        }
    }
}

이중 for문을 벗어날때 break 라벨;을하면 라벨링을 한 곳으로 빠져나갈수도 있다.

4.10 Continue

반복문 맨 처음으로 돌아간다.

public class C03Contunue {
    public static void main(String[] args) {
        //continue

        while (true) {
            System.out.println("실행문1");

            if (true) {
                continue;
            }
            System.out.println("실행문2"); //Dead code
        }
    }
}

System.out.println("실행문1");만 무한반복된다.

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if(i%2 != 0) {
                continue;
            }
            System.out.print(i + " "); //2 4 6 8 10 
        }
    }
}

이러면 홀수는 실행되지 않는다.

4.11 확인문제

4.11.1 7번

while문과 scanner의 nextLIne()메소드를 이용해서 키보드로부터 입력된 데이터로 예금출금조회종료 기능을 제공하는 코드를 작성해보세요

public class ex7 {
    public static void main(String[] args) {
        int depoist;
        int withdraw;
        int balance;
        boolean stop = false;

        Scanner sc = new Scanner(System.in);

        while (!stop) {
            System.out.println("---------------------------------");
            System.out.println("1.예금 | 2.출금 | 3.잔고 | 4.종료");
            System.out.println("---------------------------------");
            System.out.print("선택> ");

            String menu = sc.nextLine();
            switch (menu) {
            case "1":
                System.out.print("예금액> ");
                depoist = Integer.parseInt(sc.nextLine());
                break;
            case "2":
                System.out.print("출금액> ");
                withdraw = Integer.parseInt(sc.nextLine());
                break;
            case "3":
                System.out.print("잔고> ");
                balance = Integer.parseInt(sc.nextLine());
                break;
            case "4":
                System.out.print("프로그램 종료");
                stop = true;
                break;
            }
        }
    }
}

4.11.2 숫자 탑쌓기 #1

0
01
012
0123
01234

public class ex8 {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }
}

4.11.3 숫자 탑쌓기 #2

1
12
123
1234
12345

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

4.11.3 숫자 탑쌓기 #3

0
10
210
3210
43210

public class ex10 {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print(i-j);
            }
            System.out.println();
        }
    }
}

i0 j0
i1 j1j0
i2 j2j1j0
출력되는 문자를 보고 생각하면된다.

3번 강사님 풀이

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

2023.02.21 후기

break point 디버깅
step over 한줄씩 실행하는 것 볼 수있다.
재생버튼 누르면 끝까지 실행된다.
브레이킹 포인트를 기준으로 실행흐름을 보여준다.

'국비 > Java' 카테고리의 다른 글

2023.02.23 21일차 Java  (0) 2023.02.23
2023.02.22 20일차 Java  (0) 2023.02.22
2023.02.20 18일차 Java  (0) 2023.02.20
2023.02.17 17일차 Java  (0) 2023.02.17
2023.02.16 16일차 Java  (0) 2023.02.16

+ Recent posts