프로그래밍 언어/JAVA

03. 이것이 자바다 5장 확인 문제

코딩 펭귄 2021. 7. 28. 15:55
import java.util.Scanner;

public class Exercise {

	public static void main(String[] args) {
		Exercise07();
		Exercise08();
		Exercise09();
	}

	// 주어진 배열의 항목에서 최대값 구하기
	public static void Exercise07() {
		System.out.println("Exercise 07:");

		int max = 0;
		int[] array = { 1, 5, 3, 8, 2 };

		for (int i : array) {
			if (i > max) {
				max = i;
			}
		}

		System.out.println("max: " + max);
	}

	// 주어진 배열의 전체 항목의 합과 평균값 구하기
	public static void Exercise08() {
		System.out.println("Exercise 08:");

		int[][] array = { 
				{ 95, 86 }, 
				{ 83, 92, 96 }, 
				{ 78, 83, 93, 87, 88 } 
		};

		int sum = 0;
		double avg = 0.0;
		int count = 0;

		for (int[] i : array) {
			for (int j : i) {
				sum += j;
				count++;
			}
		}

		avg = (double) sum / count;

		System.out.println("sum: " + sum);
		System.out.println("avg: " + avg);
	}
	
	// 학생 수와 점수를 입력받아 최고 및 평균 점수 계산 프로그램 만들기
	public static void Exercise09() {
		System.out.println("Exercise 09: ");
		
		boolean run = true;
		int studentNum = 0;
		int[] scores = null;
		Scanner scanner = new Scanner(System.in);
		
		while(run) {
			System.out.println("-----------------------------------------------------");
			System.out.println("1. 학생 수 | 2. 점수 입력 | 3. 점수 리스트 | 4. 분석 | 5. 종료");
			System.out.println("-----------------------------------------------------");
			System.out.println("선택> ");
			
			int selectNo = scanner.nextInt();
			
			if(selectNo == 1) {
				System.out.println("학생 수> ");
				studentNum = scanner.nextInt();
				scores = new int[studentNum];
			} else if (selectNo == 2) {
				if (scores != null) {
					for (int i = 0; i < scores.length; i++) {
						System.out.println("scores[" + i + "]>");
						scores[i] = scanner.nextInt();
					}
				}
			}else if (selectNo == 3) {
				if(scores != null) {
					for (int i = 0; i < scores.length; i++) {
						System.out.println("scores[" + i + "]: "+scores[i]);
					}
				}
				
			}else if (selectNo == 4) {
				if(scores != null) {
					int max = 0;
					int sum = 0;
					double avg = 0.0;
					int count = 0;
					
					for(int i : scores) {
						if (i > max) {
							max = i;
						}
						sum += i;
						count++;
					}
					avg = (double) sum / count;
					
					System.out.println("최고 점수: " + max);
					System.out.println("평균 점수: " + avg);
				}
				
			}else if (selectNo == 5) {
				System.out.println("프로그램 종료");
				run = false;
			}else {
				System.out.println("잘못 입력하였습니다.");
			}
		}
	}
	
}

4장과 같이 각 문제마다 메소드를 만들어 main 메소드에서 한꺼번에 실행하였습니다.

 

결과는 다음과 같이 잘 출력되는 것을 확인할 수 있습니다.

 

Exercise 07

public static void Exercise07() {
	System.out.println("Exercise 07:");

	int max = 0;
	int[] array = { 1, 5, 3, 8, 2 };

	for (int i : array) {
		if (i > max) {
			max = i;
		}
	}

	System.out.println("max: " + max);
}

Exercise 07은 배열의 값 중 제일 큰 값을 출력하는 문제입니다.

향상된 for문을 사용해 배열 전체를 처음부터 끝까지 반복합니다.

이때 최대값을 저장할 max 변수를 만들어 현재 배열의 값이 max에 저장되어 있는 값보다 크다면 해당 배열 요소 값을 max에 대입합니다.

처음부터 끝까지 하나씩 비교하면 제일 큰 값을 찾아 출력할 수 있습니다.

 

Exercise 08

public static void Exercise08() {
	System.out.println("Exercise 08:");

	int[][] array = { 
			{ 95, 86 }, 
			{ 83, 92, 96 }, 
			{ 78, 83, 93, 87, 88 } 
	};

	int sum = 0;
	double avg = 0.0;
	int count = 0;

	for (int[] i : array) {
		for (int j : i) {
			sum += j;
			count++;
		}
	}

	avg = (double) sum / count;

	System.out.println("sum: " + sum);
	System.out.println("avg: " + avg);
}

Exercise 08은 2차원 배열 요소들의 합과 평균값을 구하는 문제입니다.

 

이번 문제 또한 향상된 배열을 이용하여 모든 배열 요소를 탐색합니다. 

하지만 이번에는 2차원 배열이므로 하나의 for문만으로 모든 요소를 탐색할 수 없으므로 중첩 for문을 이용합니다.

모든 배열의 요소를 탐색하여 sum 변수에 하나씩 더해주면 전체 값의 합을 출력할 수 있습니다.

 

count 변수는 평균 값을 구하기 위한 변수입니다. 

평균 값을 구하기 위해서는 배열의 요소가 몇 개인지 알아야 하기 때문에 한 번 탐색할 때마다 1을 더해줍니다.

for문은 배열 요소 수만큼 반복되기 때문에 for문 종료 시 count 값은 배열 요소 개수와 같습니다.

따라서 sum을 count로 나눠 주면 평균값을 구할 수 있습니다.

 

Exercise 09

public static void Exercise09() {
	System.out.println("Exercise 09: ");
		
	boolean run = true;
	int studentNum = 0;
	int[] scores = null;
	Scanner scanner = new Scanner(System.in);
		
	while(run) {
		System.out.println("-----------------------------------------------------");
		System.out.println("1. 학생 수 | 2. 점수 입력 | 3. 점수 리스트 | 4. 분석 | 5. 종료");
		System.out.println("-----------------------------------------------------");
		System.out.println("선택> ");
			
		int selectNo = scanner.nextInt();
		
		if(selectNo == 1) {
			System.out.println("학생 수> ");
			studentNum = scanner.nextInt();
			scores = new int[studentNum];
		} else if (selectNo == 2) {
			if (scores != null) {
				for (int i = 0; i < scores.length; i++) {
					System.out.println("scores[" + i + "]>");
					scores[i] = scanner.nextInt();
				}
			}
		}else if (selectNo == 3) {
			if(scores != null) {
				for (int i = 0; i < scores.length; i++) {
					System.out.println("scores[" + i + "]: "+scores[i]);
				}
			}
				
		}else if (selectNo == 4) {
			if(scores != null) {
				int max = 0;
				int sum = 0;
				double avg = 0.0;
				int count = 0;
					
				for(int i : scores) {
					if (i > max) {
						max = i;
					}
					sum += i;
					count++;
				}
				avg = (double) sum / count;
					
				System.out.println("최고 점수: " + max);
				System.out.println("평균 점수: " + avg);
			}
				
		}else if (selectNo == 5) {
			System.out.println("프로그램 종료");
			run = false;
		}else {
			System.out.println("잘못 입력하였습니다.");
		}
	}
}

Exercise 09는 학생 수와 학생의 점수를 직접 입력받아 최고 점수와 평균 점수를 출력하는 프로그램을 만드는 문제입니다.

 

해당 메뉴에는 1~5까지의 선택지가 있으나 메뉴 선택 시 실수로 다른 숫자를 입력할 가능성이 있으므로 else문을 이용해 잘못 입력했을 경우를 만들어줍니다.

 

메뉴 2, 3, 4는 메뉴 1이 선행된 이후에 작성할 수 있는 메뉴이기 때문에 점수가 저장되는 배열이 null인 경우에는 활성화되어서는 안 됩니다. 따라서 if문을 이용해 scores 배열이 null이 아닌 경우에만 활성화되도록 코드를 작성합니다. 

현재 코드에서는 학생 수를 입력하지 않고 메뉴 2, 3, 4를 입력했을 경우 바로 초기 메뉴로 되돌아가지만, "학생 수를 먼저 입력하세요." 등의 에러 메시지를 출력하는 것도 좋은 방법입니다.