[명품자바] 3장 실습문제

sum·2022년 7월 18일
0

명품자바

목록 보기
11/17

1

다음 프로그램에 대해 물음에 답하라?

int sum=0, i=0;
while(i<100) {
	sum=sum+i;
    i += 2;
}
System.out.println(sum);
  1. 무엇을 계산하는 코드이며 실행 결과 출력되는 내용은?
    i를 0부터 99까지 짝수만 더하는 코드로, 실행 결과는 2450이다.
  2. 위의 코드를 main() 메소드로 만들고 WhileTest 클래스로 완성하라.
public class WhileTest {
    public static void main(String[] args) {
        int sum=0, i=0;

        while(i < 100) {
            sum = sum + i;
            i += 2;
        }

        System.out.println(sum);
    }
}
  1. for 문을 이용하여 동일하게 실행되는 ForTest 클래스를 작성하라.
public class ForTest {
    public static void main(String[] args) {
        int sum=0;

        for(int i=0; i < 100; i+=2) {
            sum = sum + i;
        }

        System.out.println(sum);
    }
}
  1. do-while 문을 이용하여 동일하게 실행되는 DoWhileTest 클래스를 작성하라.
public class DoWhileTest {
    public static void main(String[] args) {
        int sum=0, i=0;

        do {
            sum = sum + i;
            i += 2;
        } while(i < 100);

        System.out.println(sum);
    }
}

2

다음 2차원 배열 n을 출력하는 프로그램을 작성하라.

int n[][] = {{1}, {1,2,3}, {1}, {1,2,3,4}, {1,2}};

코드

public class Arr2 {
    public static void main(String[] args) {
        int n[][] = {{1}, {1,2,3}, {1}, {1,2,3,4}, {1,2}};

        for(int i=0; i<n.length; i++) {
            for(int j=0; j<n[i].length; j++) {
                System.out.print(n[i][j]+" ");
            }
            
            System.out.println();
        }
    }
}

출력

1 
1 2 3 
1 
1 2 3 4 
1 2 

3

Scanner를 이용하여 정수를 입력받고 다음과 같이 *를 출력하는 프로그램을 작성하라. 다음은 5를 입력받았을 경우이다.

코드

import java.util.Scanner;

public class PrintStar {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("정수를 입력하시오>>");
        int num = sc.nextInt();

        for(int i=0; i<num; i++) {
            for(int j=0; j<num-i; j++) {
                System.out.print("*");
            }

            System.out.println("");
        }

        sc.close();
    }
}

출력

정수를 입력하시오>>5
*****
****
***
**
*

4

Scanner를 이용하여 소문자 알파벳을 하나 입력받고 다음과 같이 출력하는 프로그램을 작성하라. 다음은 e를 입력받았을 경우이다.

코드

import java.util.Scanner;

public class PrintAlphabet {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("소문자 알파벳 하나를 입력하시오>>");
        String s = sc.next(); // 문자열 읽기
        char c = s.charAt(0); // 문자열의 첫 번째 문자를 c에 입력

        for(int i=0; i<=c-'a'; i++) {
            for(char j='a'; j<= c-i; j++) {
                System.out.print(j);
            }

            System.out.println("");
        }

        sc.close();
    }
}

출력

소문자 알파벳 하나를 입력하시오>>e
abcde
abcd
abc
ab
a

5

양의 정수를 10개 입력받아 배열에 저장하고, 배열에 저장하고, 배열에 있는 정수 중에서 3의 배수만 출력하는 프로그램을 작성하라.

코드

import java.util.Scanner;

public class Print3MulFrom10IntArr {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int arr[] = new int[10];

        System.out.print("양의 정수 10개를 입력하시오>>");
        for(int i=0; i<arr.length; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.print("3의 배수는 ");
        for(int i=0; i<arr.length; i++) {
            if(arr[i]%3 == 0) {
                System.out.print(arr[i]+" ");
            }
        }

        sc.close();
    }
}

출력

양의 정수 10개를 입력하시오>> 3 27 39 27 10 37 23 51 33 20
3의 배수는 3 27 39 27 51 33 

6

배열과 반복문을 이용하여 프로그램을 작성해보자. 키보드에서 정수로 된 돈의 액수를 입력받아 오만 원권, 만 원권, 천 원권, 500원짜리 동전, 100원짜리 동전, 50원짜리 동전, 10원짜리 동전, 1원짜리 동전이 각 몇 개로 변환되는지 예시와 같이 출력하라. 이때 반드시 다음 배열을 이용하고 반복문으로 작성하라.

int[] unit = {50000, 10000, 1000, 500, 100, 50, 10, 1}; // 환산할 돈의 종류

코드

import java.util.Scanner;

public class ExchangeMoney {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] unit = {50000, 10000, 1000, 500, 100, 50, 10, 1}; // 환산할 돈의 종류

        System.out.print("금액을 입력하시오>>");
        int money = sc.nextInt();

        for (int i=0; i<unit.length; i++) {
            System.out.printf("%d원 짜리 : %d개\n", unit[i], money/unit[i]);
            money = money - (money/unit[i])*unit[i];
        }

        sc.close();
    }
}

출력

금액을 입력하시오>>35235
50000원 짜리 : 0개
10000원 짜리 : 3개
1000원 짜리 : 5개
500원 짜리 : 0개
100원 짜리 : 2개
50원 짜리 : 0개
10원 짜리 : 3개
1원 짜리 : 5개

7

정수를 10개 저장하는 배열을 만들고 1에서 10까지 범위의 정수를 랜덤하게 생성하여 배열에 저장하라. 그리고 배열에 든 숫자들과 평균을 출력하라.

코드

public class PrintNumAndArrFromRand10IntArr {
    public static void main(String[] args) {
        int arr[] = new int[10];
        double sum=0;

        System.out.print("랜덤한 정수들 : ");
        for(int i=0; i<arr.length; i++) {
            arr[i] = (int)(Math.random()*10+1);
            System.out.print(arr[i]+" ");
            sum += arr[i];
        }
        System.out.println();
        System.out.print("평균은 "+sum/arr.length);
    }
}

출력

랜덤한 정수들 : 8 3 2 7 1 7 7 7 7 2 
평균은 5.1

8

정수를 몇 개 저장할지 키보드로부터 개수를 입력받아(100보다 작은 개수) 정수 배열을 생성하고, 이곳에 1에서 100까지 범위의 정수를 랜덤하게 삽입하라. 배열에는 같은 수가 없도록 하고 배열을 출력하라.

코드

import java.util.Scanner;

public class RandIntArrWithoutDuplication {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("정수 몇 개?");
        int num = sc.nextInt();
        int arr[] = new int[num];

        for(int i=0; i<arr.length; i++) {
            arr[i] = (int) (Math.random() * 100 + 1);

            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) i--;
            }
        }

        for(int i=0; i<arr.length; i++) {
            System.out.print(arr[i]+" ");

            if((i+1)%10 == 0)
                System.out.println();
        }

        sc.close();
    }
}

출력

정수 몇 개?24
40 88 42 50 46 70 95 100 32 44 
93 26 27 65 99 85 63 15 34 18 
36 29 43 92 

9

4x4의 2차원 배열을 만들고 이곳에 1에서 10까지 범위의 정수를 랜덤하게 생성하여 정수 16개를 배열에 저장하고, 2차원 배열을 화면에 출력하라.

코드

public class PrintArr2 {
    public static void main(String[] args) {
        int arr[][] = new int[4][4];

        for(int i=0; i<4; i++) {
            for(int j=0; j<4; j++) {
                arr[i][j] = (int)(Math.random()*10+1);
                System.out.printf("%2d",arr[i][j]);
            }

            System.out.println();
        }
    }
}

출력

 5 3 4 1
 7 9 2 3
 3 3 4 6
 2 7 3 4

10

4 x 4의 2차원 배열을 만들고 이곳에 1에서 10까지 범위의 정수를 10개만 랜덤하게 생성하여 임의의 위치에 삽입하라. 동일한 정수가 있어도 상관없다. 나머지 6개의 숫자는 모두 0이다. 만들어진 2차원 배열을 화면에 출력하라.

코드

public class Print10IntFromArr2 {
    public static void main(String[] args) {
        int arr[][] = new int[4][4];
        int count=0;

        for(int i=0; i<4; i++) {
            for(int j=0; j<4; j++){
                arr[i][j] = 0;
            }
        }

        while(count<10) {
            int row = (int)(Math.random()*4);
            int col = (int)(Math.random()*4);

            if(arr[row][col] != 0) {
                continue;
            } else {
                arr[row][col] = (int)(Math.random()*9+1);
                count++;
            }
        }

        for(int i=0; i<4; i++) {
            for(int j=0; j<4; j++) {
                System.out.print(arr[i][j]+"\t");
            }

            System.out.println();
        }
    }
}

출력

0	1	0	9	
2	7	7	2	
1	2	9	0	
7	0	0	0	

11

다음과 같이 작동하는 Average.java를 작성하라. 명령행 인자는 모두 정수만 사용되며 정수들의 평균을 출력한다. 다음 화면은 컴파일된 Average.class 파일을 c:\Temp 디렉터리에 복사한 뒤 실행한 경우이다. 원본 Average.class 파일은 이클립스의 프로젝트 폴더 밑에 bin 폴더에 있다.

코드

package p3;

public class Average {
    public static void main(String[] args) {
        int sum=0;
        for(int i=0; i<args.length;i++) {
            sum += Integer.parseInt(args[i]);
        }
        System.out.println(sum/args.length);
    }
}

출력

12

다음과 같이 작동하는 Add.java를 작성하라. 명령행 인자 중에서 정수 만을 골라 합을 구하라. 다음 화면은 Add.class 파일을 c:\Temp 디렉터리에 복사한 뒤 실행한 경우이다. 원본 Add.class 파일은 이클립스 프로젝트 폴더 밑에 bin 폴더에 있다.

코드

package p3;

public class Add {
    public static void main(String[] args) {
        int sum=0;
        for(int i=0; i<args.length;i++) {
            try {
                sum += Integer.parseInt(args[i]);
            } catch (NumberFormatException e) {
                continue;
            }
        }
        System.out.println(sum);
    }
}

출력

13

반복문을 이용하여 369게임에서 박수를 쳐야 하는 경우를 순서대로 화면에 출력해보자. 1부터 시작하며 99까지만 한다. 실행 사례는 다음과 같다.

코드

public class Game369 {
    public static void main(String[] args) {
        int i=1;
        while (i<100) {
            int count=0;

            if(i/10==3 || i/10==6 || i/10==9)   count++;
            if(i%10==3 || i%10==6 || i%10==9)   count++;

            if(count==1)   System.out.println(i+" 박수 짝");
            else if(count==2)   System.out.println(i+" 박수 짝짝");
            i++;
        }
    }
}

출력

3 박수 짝
6 박수 짝
9 박수 짝
13 박수 짝
16 박수 짝
19 박수 짝
23 박수 짝
26 박수 짝
29 박수 짝
30 박수 짝
31 박수 짝
32 박수 짝
33 박수 짝짝
34 박수 짝
35 박수 짝
36 박수 짝짝
37 박수 짝
38 박수 짝
39 박수 짝짝
43 박수 짝
46 박수 짝
49 박수 짝
53 박수 짝
56 박수 짝
59 박수 짝
60 박수 짝
61 박수 짝
62 박수 짝
63 박수 짝짝
64 박수 짝
65 박수 짝
66 박수 짝짝
67 박수 짝
68 박수 짝
69 박수 짝짝
73 박수 짝
76 박수 짝
79 박수 짝
83 박수 짝
86 박수 짝
89 박수 짝
90 박수 짝
91 박수 짝
92 박수 짝
93 박수 짝짝
94 박수 짝
95 박수 짝
96 박수 짝짝
97 박수 짝
98 박수 짝
99 박수 짝짝

14

다음 코드와 같이 과목과 점수가 짝을 이루도록 2개의 배열을 작성하라.

String course[] = {"Java", "C++", "HTML5", "컴퓨터구조", "안드로이드"};
int score[]  = {95, 88, 76, 62, 55};

그리고 다음 예시와 같이 과목 이름을 입력받아 점수를 출력하는 프로그램을 작성하라. "그만"을 입력받으면 종료한다.

코드

import java.util.Scanner;

public class CourseAndScoreOfArr {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String course[] = {"Java", "C++", "HTML5", "컴퓨터구조", "안드로이드"};
        int score[] = {95, 88, 76, 62, 55};
        String name; //사용자가 입력한 과목명
        int i=0;

        while (true) {
            System.out.print("과목 이름>>");
            name = sc.next();

            if(name.equals("그만"))   break;

            for(i=0; i<course.length; i++){
                if(course[i].equals(name)) {
                    System.out.println(course[i] + "의 점수는 " + score[i]);
                    break;
                }
            }

            if(i == course.length) {
                System.out.println("없는 과목입니다.");
            }
        }

        sc.close();
    }
}

출력

과목 이름>>JAVA
없는 과목입니다.
과목 이름>>Java
Java의 점수는 95
과목 이름>>안드로이드
안드로이드의 점수는 55
과목 이름>>그만

15

코드

public class Multiply {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (true) {
            System.out.print("곱하고자 하는 두 수 입력>>");
            try {
                int n = sc.nextInt();
                int m = sc.nextInt();
                System.out.println(n+"X"+m+"="+n*m);
                break;
            } catch (InputMismatchException e) {
                System.out.println("실수는 입력하면 안 됩니다.");
                sc.nextLine();
                continue;
            }
        }

        sc.close();
    }
}

출력

곱하고자 하는 두 수 입력>>2 3.8
실수는 입력하면 안 됩니다.
곱하고자 하는 두 수 입력>>2 4
2X4=8

16

컴퓨터와 독자 사이의 가위 바위 보 게임을 만들어보자. 예시는 다음 그림과 같다. 독자부터 먼저 시작한다. 독자가 가위 바위 보 중 하나를 입력하고 Enter키를 치면, 프로그램은 가위 바위 보 중에서 랜덤하게 하나를 선택하고 컴퓨터가 낸 것으로 한다. 독자가 입력한 값과 랜덤하게 선택한 값을 비교하여 누가 이겼는지 판단한다. 독자가 가위 바위 보 대신 "그만"을 입력하면 게임을 끝난다.

코드

import java.util.Scanner;

public class GameRPS {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str[] = {"가위", "바위", "보"};

        System.out.println("컴퓨터와 가위 바위 보 게임을 합니다.");
        System.out.print("가위 바위 보!>>");
        String option = sc.next();

        while (!option.equals("그만")) {
            int n = (int)(Math.random()*3);
            System.out.print("사용자 = "+option+", 컴퓨터 = "+str[n]+", ");
            if(n==0) {
                switch (option) {
                    case "가위":
                        System.out.println("비겼습니다.");
                        break;
                    case "바위":
                        System.out.println("사용자가 이겼습니다.");
                        break;
                    case "보":
                        System.out.println("컴퓨터가 이겼습니다.");
                        break;
                    default:
                        break;
                }
            } else if(n==1) {
                switch (option) {
                    case "가위":
                        System.out.println("컴퓨터가 이겼습니다.");
                        break;
                    case "바위":
                        System.out.println("비겼습니다.");
                        break;
                    case "보":
                        System.out.println("사용자가 이겼습니다.");
                        break;
                    default:
                        break;
                }
            } else {
                switch (option) {
                    case "가위":
                        System.out.println("사용자가 이겼습니다.");
                        break;
                    case "바위":
                        System.out.println("컴퓨터가 이겼습니다.");
                        break;
                    case "보":
                        System.out.println("비겼습니다.");
                        break;
                    default:
                        break;
                }
            }

            System.out.print("가위 바위 보!>>");
            option=sc.next();

            if(option.equals("그만"))
                System.out.println("게임을 종료합니다.");
        }
        sc.close();
    }
}

출력

컴퓨터와 가위 바위 보 게임을 합니다.
가위 바위 보!>>보
사용자 = 보, 컴퓨터 = 보, 비겼습니다.
가위 바위 보!>>보
사용자 = 보, 컴퓨터 = 가위, 컴퓨터가 이겼습니다.
가위 바위 보!>>보
사용자 = 보, 컴퓨터 = 바위, 사용자가 이겼습니다.
가위 바위 보!>>가위
사용자 = 가위, 컴퓨터 = 보, 사용자가 이겼습니다.
가위 바위 보!>>그만
게임을 종료합니다.

0개의 댓글