package kr.s06.array;
import java.util.Scanner;
public class ArrayMain07 {
public static void main(String[] args) {
//값을 직접 배열에 입력하여 성적 처리하는 프로그램 만들기
Scanner input = new Scanner(System.in);
String[] course = {"국어", "영어", "수학"};
int[] score = new int[course.length];
int sum = 0;
float avg = 0.0f;
//반복문을 이용해서 입력 처리
for(int i=0;i<score.length;i++) {
do {
System.out.print(course[i] + "=");
score[i] = input.nextInt();
}while(score[i] < 0 || score[i] > 100);
//총점 구하기
sum += score[i];
}
//평균 구하기
avg = sum / (float)course.length; //=score.length
System.out.println(); //단순 줄바꿈
//과목 점수 출력
for(int i=0;i<score.length;i++) {
System.out.printf("%s = %d%n", course[i], score[i]);
}
//총점과 평균 출력
System.out.printf("총점 = %d%n", sum);
System.out.printf("평균 = %.2f%n", avg);
input.close();
}
}
먼저 과목명을 저장할 배열(course)을 만든다(선언, 생성, 초기화). String[] course = {"국어", "영어", "수학"};
다음은 성적을 저장할 배열 (score)을 선언 및 생성하는데, 과목명을 저장한 course 배열과 길이를 같게 만들어 주기 위해 길이가 들어갈 자리에 course 배열의 길이를 명시한다. int[] score = new int[course.length];
연산 결과를 저장하기 위해 총점을 저장할 변수와 평균을 저장할 변수를 만들어 준다. int sum = 0;, float avg = 0.0f;
for문을 통해 입력 받은 과목 점수를 score 배열에 저장해 주는데, 이때 do~while문을 활용해 입력한 값이 음수거나 100 이상이면 재입력하게 조건 체크를 해준다.
for(int i=0;i<score.length;i++) {
do {
System.out.print(course[i] + "=");//과목명 입력칸
score[i] = input.nextInt();//위에 생성된 배열에 직접 입력
}while(score[i] < 0 || score[i] > 100);
sum += score[i];
}
while문이 아닌 do~while문을 사용하는 이유
while문은 조건이 true일 때 수행문을 수행하는 것만 가능하기 때문에 입력한 값이 음수거나 100 이상일 경우에 대한 조건 처리가 불가하기 때문이다.
따라서 do 블럭에서 과목명을 입력 받아 score[i] = input.nextInt(); score 배열에 직접 저장하는데, 만약 while(score[i] < 0 || score[i] > 100)'; 그 값이 음수이거나 100 이상이라면 조건이 true가 되어 do 블럭으로 돌아가 재입력을 하게 된다.
그렇게 입력된 성적은 루프를 돌며(for문) sum 변수에 누적된다.
다음으로는 총점을 과목수로 나누어 평균을 구하는데, 이때 과목수는 배열의 길이와 같고 sum과 배열의 길이 모두 int므로 실수로 다음과 같이 avg = sum / (float)course.length; 강제 형변환을 해준다.
이때 course.length 대신 score.length를 입력해도 동일한 결과가 나온다.
for문을 통해 course 배열과 score 배열에 저장된 과목명과 각 점수를 출력한다.
for(int i=0;i<score.length;i++) {
System.out.printf("%s = %d%n", course[i], score[i]);
}
System.out.printf("총점 = %d%n", sum);
System.out.printf("평균 = %.2f%n", avg);
input.close(); 해준다.