조건문과 반복문 연습문제_자바의

4-1 다음 문장을 조건식으로 나타내라

① int 변수 x가 10보다 크고 20보다 작으면 참인 조건식

② char 변수 ch가 공백이나 탭이 아니면 참이 되는 조건식

③ char 변수 ch가 ‘x’ 또는 ‘X’이면 참이 되는 조건식

④ char 변수 ch가 숫자(‘0’~’9’)이면 참이 되는 조건식

⑤ char ch 타입의 변수는 영문자(대소문자 모두 참인 조건식)

⑥ int 변수 year가 400의 배수이거나 4의 배수이고 100의 배수가 아니면 참인 조건식

⑦ boolean 변수 powerOn이 false일 때 true가 되는 조건식

⑧ 문자열 참조 변수 str이 “yes”이면 참인 조건식.

1. 10 < x && x < 20
2. !(ch = "" || ch = "\t")
3. ch = "x" || ch = "X"
4. '0' < ch && ch < '9'
5. 'a' < char < 'z' || 'A' < char < 'Z'
6. year % 400 == 0 ||( year % 4 == 0 && year % 100 !=0)
7. powerOn == false
8. str.equals("yes")

같음과 ==의 차이점

심지어 () ==
모양의 차이 방법으로 객체 사이의 내용
비교할 수 있습니다
비교 연산자
비교의 차이 비교 대상의
내용을 비교하다
주소 값 비교

4-2 1부터 20까지 2와 3의 배수가 아닌 정수의 합을 구하시오.

public class Practice02 {
    public static void main(String() args) {
        int sum = 0;
        for (int i = 1; i <= 20; i++) {
            if (!(i % 2 == 0 || i % 3 == 0)) {
                sum += i;
            }
        }
        System.out.println(sum);
    }
}
---------------------------------------------------------------------------------------------
(결과)
73

4-3 1 + (1+2) + (1+2+3) + (1+2+3+…+10)의 결과를 계산합니다.

public class Practice03 {
    public static void main(String() args) {
        int sum = 0;
        for (int i = 1; i <= 10; i++) {
            for (int j = 1; j <= i; j++) {
                sum += j;
            }
        }
        System.out.println(sum);
    }
}
---------------------------------------------------------------------------------------------
(결과)
220

4-4 1 + (-2) + (3) + (-4) + …가 계속되면 합계가 100 이상이 되려면 몇 번을 더해야 합니까?

public class Practice04 {
    public static void main(String() args) {
        int i = 1;
        int j = 1;
        int num = 0;
        int sum = 0;

        while (true) {
            num = i * j;
            j *= (-1);
            sum += num;
            
            if (sum >= 100) {
                break;
            }

            i++;
        }
        System.out.println(num);
        System.out.println(sum);
    }
}
---------------------------------------------------------------------------------------------
(결과)
199
100

4-5 다음 for문을 while문으로 변경

진술에

public class Practice05 {
    public static void main(String() args) {
        for (int i = 0; i <= 10; i++) {
            for (int j = 0; j <= i; j++)
                System.out.print("*");
            System.out.println();
        }
    } // end of main
} // end of class
---------------------------------------------------------------------------------------------
(결과)

while 문

public class Practice05 {
    public static void main(String() args) {
        int i = 0;
        while (i <= 10) {
            int j = 0;
            while (j <= i) {
                System.out.println("*");
                j++;
            }
            System.out.println();
            i++;
        }
    }
}
---------------------------------------------------------------------------------------------
(결과)
*

*
*

*
*
*

*
*
*
*

*
*
*
*
*

*
*
*
*
*
*

*
*
*
*
*
*
*

*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*

4-6 두 개의 주사위를 굴렸을 때 주사위의 합이 6인 경우의 수를 모두 출력하는 프로그램을 작성하시오.

public class Practice06 {
    public static void main(String() args) {
        for (int i = 1; i <=6 ; i++) {
            for (int j = 1; j <=6 ; j++) {
                if (i + j == 6) {
                    System.out.println(i + "," + j);
                }
            }
        }

    }
}
---------------------------------------------------------------------------------------------
(결과)
1,5
2,4
3,3
4,2
5,1

4~7자리의 문자열이 주어졌을 때 각 자릿수의 합을 더한 결과를 주는 코드를 완성하시오. 문자열이 “12345”이면 “1+2+3+4+5″의 결과인 15를 반환해야 합니다. 올바른 코드를 입력하세요

public class Practice07 {
    public static void main(String() args) {
        String str = "12345";
        int sum = 0;

        for (int i = 0; i < str.length(); i++) {
            sum += Integer.parseInt(str.valueOf(i + 1));
        }
        
        System.out.println("sum = " + sum);
    }
}

---------------------------------------------------------------------------------------------
(결과)
sum = 15

4-8 Math.random()을 이용하여 1에서 6 사이의 정수를 변수 값에 저장하는 코드를 완성하세요.

public class Practice08 {
    public static void main(String() args) {
        int value = 0;

        for (int i = 0; i <= 5; i++) {
            value = (int) (Math.random() * 6) + 1;
            System.out.println("value : " + value);
        }
    }
}

---------------------------------------------------------------------------------------------
(결과)
value : 1
value : 4
value : 6
value : 5
value : 6
value : 2

4-9 int형 변수 num이 있을 경우 각 자리의 합을 더한 결과를 출력하는 코드를 완성하시오. 변수 num의 값이 12345이면 ‘1+2+3+4+5’의 결과인 15를 출력

public class Practice09 {
    public static void main(String() args) {
        int num = 12345;
        int sum = 0;

        while (num != 0) {
            sum += num % 10;
            num /= 10;
        }
        System.out.println("sum = " + sum);
    }
}
---------------------------------------------------------------------------------------------
(결과)
sum = 15

4-10 다음은 숫자 추측 게임입니다. 1에서 100 사이의 값을 반복해서 입력하고 추측한 값을 컴퓨터가 추측하면 게임이 종료됩니다. 사용자가 값을 입력하면 컴퓨터는 사용자가 생각하고 전달하는 값과 비교합니다. 컴퓨터가 생각한 숫자를 사용자가 맞추면 게임이 종료되고 숫자를 몇 번 맞혔는지 알려줍니다. 프로그램을 완료하려면 코드를 입력하세요.

import java.util.Scanner;

public class Practice10 {
    public static void main(String() args) {
        // 1~100 사이의 임의의 값을 얻어서 answer에 저장
        int answer = (int) (Math.random() * 100) + 1;
        int input = 0; // 사용자 입력을 저장할 공간
        int count = 0; // 시도 횟수를 세기 위한 공간

        Scanner sc = new Scanner(System.in);

        do {
            count++;
            System.out.println("1과 100 사이의 값을 입력하세요 : ");
            input = sc.nextInt();

            if (answer > input) {
                System.out.println("더 큰 수를 입력하세요");
                continue;
            } else if (answer < input) {
                System.out.println("더 작은 수를 입력하세요");
                continue;
            } else {
                System.out.println("맞혔습니다.");
                break;
            }
        } while (true);
        System.out.println("시도횟수는 " + count +"입니다.");
    }
}

---------------------------------------------------------------------------------------------
(결과)
1과 100 사이의 값을 입력하세요 : 
50
더 작은 수를 입력하세요
1과 100 사이의 값을 입력하세요 : 
30
더 작은 수를 입력하세요
1과 100 사이의 값을 입력하세요 : 
10
더 큰 수를 입력하세요
1과 100 사이의 값을 입력하세요 : 
25
더 작은 수를 입력하세요
1과 100 사이의 값을 입력하세요 : 
20
더 작은 수를 입력하세요
1과 100 사이의 값을 입력하세요 : 
17
더 큰 수를 입력하세요
1과 100 사이의 값을 입력하세요 : 
18
맞혔습니다.
시도횟수는 7입니다.