JAVA/명품 JAVA Programming

[(개정판 4판) 명품 JAVA Programming] 3장 실습 문제

최옥구 2023. 1. 24. 23:00
반응형

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

(1) 0부터 100미만까지의 짝수들의 합계를 구하는 프로그램이다.

int sum = 0, i = 0;
while(i < 100){
    sum = sum + i;
    i += 2;
}
System.out.println(sum);

 

[(2) 위의 코드를 main() 메소드로 만들고 WhileTest 클래스로 만들어라.] 

import java.util.Scanner;

public class App{
	public static int WhileTest(int sum, int i) {
		while(i < 100) {
			sum = sum + i;
			i += 2;
		}
		return sum;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int sum = 0, i = 0;
		sum = WhileTest(sum, i);
		System.out.println(sum);
	}
}

 

[(3) for 문을 이용하여 동일하게 실행되는 ForTest 클래스를 작성하라. ]

import java.util.Scanner;

public class App{
	public static int ForTest() {
		int sum = 0;
		for(int i = 0; i < 100; i += 2) {
			sum += i;
		}
		return sum;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int sum = 0;
		sum = ForTest();
		System.out.println(sum);
	}
}

 

[(4) do-while 문을 이용하여 동일하게 실행되는 DoWhileTest 클래스를 작성하라.]

import java.util.Scanner;

public class App{
	public static int DoWhileTest() {
		int sum = 0, i = 0;
		do {
			sum += i;
			i += 2;
		}while(i < 100);
		
		return sum;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int sum = 0;
		sum = DoWhileTest();
		System.out.println(sum);
	}
}

 


 

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

[결과]

[소스 코드]

import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		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.print("\n");
		}
	}
}

 


 

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

[결과]

[소스 코드]

import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		System.out.print("정수를 입력하시오 >> ");
		int cnt = input.nextInt();
		
		for(int i = 0; i < cnt; i++) {
			for(int j = 0; j < cnt - i; j++)
				System.out.print("*");
			System.out.print("\n");
		}
	}
}

 


 

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

[결과]

[소스 코드]

import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		System.out.print("소문자 알파벳 하나를 입력하시오. >> ");
		String alpha = input.next();
		char cAlpha = alpha.charAt(0);
		char Alpha;
		int cnt = (int)cAlpha - 97;
		
		for(int i = 0; i <= cnt; i++) {
			Alpha = 'a';
			for(int j = 0; j <= cnt - i; j++, Alpha++) {
				System.out.print(Alpha);
			}
			System.out.print("\n");
		}
	}
}

 


 

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

[결과]

[소스 코드]

import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		System.out.print("양의 정수 10개를 입력하시오. >> ");
		int intArray[] = new int[10];
		for(int i = 0; i < 10; i++) {
			intArray[i] = input.nextInt();
		}
		System.out.print("3의 배수는 ");
		for(int i = 0; i < 10; i++) {
			if(intArray[i] % 3 == 0) {
				System.out.print(intArray[i] + " ");
			}
		}
	}
}

 


 

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

[결과]

[소스 코드]

import java.util.Arrays;
import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		System.out.print("금액을 입력하시오. >> ");
		int money = input.nextInt();
		int unit[] = {50000, 10000, 1000, 500, 100, 50, 10, 1};
		int cnt[] = new int[8];
		Arrays.fill(cnt,0);
		while(money > 0) {
			if(money >= 50000) {
				money -= 50000;
				cnt[0]++;
				continue;
			}
			else if(money >= 10000) {
				money -= 10000;
				cnt[1]++;
				continue;
			}
			else if(money >= 1000) {
				money -= 1000;
				cnt[2]++;
				continue;
			}
			else if(money >= 500) {
				money -= 500;
				cnt[3]++;
				continue;
			}
			else if(money >= 100) {
				money -= 100;
				cnt[4]++;
				continue;
			}
			else if(money >= 50) {
				money -= 50;
				cnt[5]++;
				continue;
			}
			else if(money >= 10) {
				money -= 10;
				cnt[6]++;
				continue;
			}
			else if(money >= 1) {
				money -= 1;
				cnt[7]++;
				continue;
			}
		}
		for(int i = 0; i < 8; i++) {
			if(cnt[i] == 0)
				continue;
			System.out.println(unit[i] + "원 짜리 : " + cnt[i] + "개");
		}
	}
}

 


 

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

[결과]

[소스 코드]

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int rndArray[] = new int[10];
		double sum = 0, regular = 0;;
		for(int i = 0; i < 10; i++) {
			int rnd = (int)(Math.random()* 10 + 1);
			rndArray[i] = rnd;
		}
		System.out.print("랜덤한 정수들 : ");
		for(int i = 0; i < 10; i++) {
			System.out.print(rndArray[i] + " ");
			sum += rndArray[i];
		}
		regular = sum / 10.0;
		System.out.print("\n평균은 " + regular);
	}
}

 


반응형

 

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

[결과]

[소스 코드]

import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		System.out.print("정수 몇개? ");
		int cnt, j = 0;
		while(true) {
			cnt = input.nextInt();
			if(cnt >= 100) System.out.println("100보다 작은 숫자를 입력하세요.");
			else if(cnt < 100)
				break;
		}
		int Array[] = new int[cnt];
		for(int i = 0; i < cnt; i++) {
			int rnd = (int)(Math.random() * 100 + 1);
			Array[i] = rnd;
			while(i > 0) {
				if(Array[i] == Array[j]) {
					rnd = (int)(Math.random() * 100 + 1);
					Array[i] = rnd;
					j = 0;
				}
				j++;
				if(i <= j) {
					j = 0;
					break;
				}
					
			}
			
		}
		for(int i = 0, k = 1; i < cnt; i++, k++) {
			System.out.print(Array[i] + "  ");
			if(k % 10 == 0) System.out.print("\n");
		}
	}
}

 


 

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

[결과]

[소스 코드]

import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		int Array[][] = new int[4][4];
		
		for(int i = 0; i < 4; i++) {
			for(int j = 0; j < 4; j++) {
				int rnd = (int)(Math.random() * 10 + 1);
				Array[i][j] = rnd;
			}
		}
		
		for(int i = 0; i < 4; i++) {
			for(int j = 0; j < 4; j++) {
				System.out.print(Array[i][j] + "\t");
			}
			System.out.print("\n");
		}
	}
}

 


 

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

[결과]

[소스 코드]

import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		int Array[][] = new int[4][4];
		
		for(int i = 0; i < 4; i++) {
			for(int j = 0; j < 4; j++) {
				int rnd = (int)(Math.random() * 10 + 1);
				Array[i][j] = rnd;
			}
		}
		
		int cnt = 1;
		while(cnt <= 6) {
			int i = (int)(Math.random() * 3);
			int j = (int)(Math.random() * 3);
			if(Array[i][j] == 0) continue;
			Array[i][j] = 0;
			cnt++;
		}
		
		for(int i = 0; i < 4; i++) {
			for(int j = 0; j < 4; j++) {
				System.out.print(Array[i][j] + "\t");
			}
			System.out.print("\n");
		}
	}
}

 


 

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

[결과]

[소스 코드]

public class Average{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int sum = 0;
		for(int i = 0; i < args.length; i++) {
			int num = Integer.parseInt(args[i]);
			sum += num;
		}
		System.out.print(sum / args.length);
	}
}

 


 

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

[결과]

[소스 코드]

public class Add{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int sum = 0;
		for(int i = 0; i < args.length; i++) {
			try {
			int num = Integer.parseInt(args[i]);
			sum += num;
			}
			catch(NumberFormatException e) {
				continue;
			}
		}
		System.out.print(sum);
	}
}

 


 

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

[결과]

[소스 코드]

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(int i = 1; i < 100; i++) {
			if(i > 10) {
				int b = i % 10;
				int a = (i - b) / 10;
				if(a % 3 == 0 || a % 6 == 0 || a % 9 == 0) {
					if(b != 0 && (b % 3 == 0 || b % 6 == 0 || b % 9 == 0)) {
						System.out.println(i + " 박수 짝 짝");
					}
					else System.out.println(i + " 박수 짝");
				}
				else if(b != 0 && (b % 3 == 0 || b % 6 == 0 || b % 9 == 0)) {
					System.out.println( i + " 박수 짝");
				}
			}
			else if(i % 3 == 0 || i % 6 == 0 || i % 9 == 0) {
				System.out.println(i + " 박수 짝");
			}
		}
	}
}

 


 

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

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

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

[결과]

[소스 코드]

import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		String course [] = {"Java" , "C++", "HTML5", "컴퓨터구조", "안드로이드"};
		int score [] = {95, 88, 76, 62, 55};
		
		while(true) {
			int scr = 0;
			System.out.print("과목 이름 >> ");
			String search = input.nextLine();
			if(search.equals("그만")) break;
			for(int i = 0; i < course.length; i++) {
				if(course[i].equals(search)) {
					scr = score[i];
					System.out.println(course[i] + " 의 점수는 " + score[i]);
					break;
				}
			}
			if(scr == 0) {
				System.out.println("없는 과목입니다.");
				continue;
			}
		}
	}
}

 


 

15. 다음은 2개의 정수를 입력 받아 곱을 구하는 Multyply 클래스이다.

import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		System.out.print("곱하고자 하는 두 수 입력 >> ");
		int n = input.nextInt();
		int m = input.nextInt();
		System.out.print(n + " x " + m + " = " + n * m);
		input.close();
	}
}

다음과 같이 실행할 때 프로그램은 10과 5를 곱해 50을 잘 출력한다. 

하지만, 다음과 같이 실수를 입력하였을 때, 예외가 발생한다.

다음과 같이 실수가 입력되면 정수를 다시 입력하도록 하여 예외 없이 정상적으로 처리되도록 예외 처리 코드를 삽입하여 Multiply 클래스를 수정하라.

[결과]

[소스 코드]

import java.util.InputMismatchException;
import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		while(true) {
			System.out.print("곱하고자 하는 두 수 입력 >> ");
			try {
				int n = input.nextInt();
				int m = input.nextInt();
				System.out.print(n + " x " + m + " = " + n * m);
				break;
			}
			catch(InputMismatchException e) {
				System.out.println("실수는 입력하면 안됩니다.");
				input.nextLine();
			}	
		}
		input.close();
	}
}

 


 

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

[결과]

[소스 코드]

import java.util.InputMismatchException;
import java.util.Scanner;

public class App{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		String str[] = {"가위", "바위", "보"};
		System.out.println("컴퓨터와 가위 바위 보 게임을 합니다.");
		while(true) {
			System.out.print("가위 바위 보! >> ");
			String userInput = input.nextLine();
			if(userInput.equals("그만")) {
				System.out.print("게임을 종료합니다...");
				break;
			}
			int cmp = (int)(Math.random() * 2);
			String cmpOutput = str[cmp];
			System.out.print("사용자 = " + userInput + " 컴퓨터 = " + cmpOutput);
			if(userInput.equals(cmpOutput)) System.out.println(", 비겼습니다.");
			else if(userInput.equals("가위") && cmpOutput.equals("보") || userInput.equals("보") && cmpOutput.equals("바위") || userInput.equals("바위") && cmpOutput.equals("가위"))
				System.out.println(", 사용자가 이겼습니다.");
			else System.out.println(", 컴퓨터가 이겼습니다.");
		}
	}
}
반응형