Coding/JAVA

[JAVA]2차원 배열 예제 - 학생 점수 평균 구하기

민톨이 2024. 8. 2. 22:11
728x90

📋 입력

 public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[][] scores = new int[4][3]; // 4 = 학생 4명 / 3 = 과목 3개
        String[] subjects = {"국어","영어","수학"};

        //입력
        for(int i=0; i<4; i++){ // i = 행
            System.out.println((i+1) + "번 학생의 성적을 입력하세요:");
            for(int j=0; j<3; j++) { // j = 열
                System.out.println(subjects[j] + " 점수:");
                scores[i][j] = scanner.nextInt();
            }
        }

 

- 학생이 4명이고 과목이 3개니까 int[4][3]의 4행 3열로 배열 선언

 

📋 출력

 //출력
        for(int i=0; i<4; i++){
            int total = 0;
            for(int j=0; j <3; j++){
                total += scores[i][j];
            }
            double average = total / 3.0; //3과목이니께 3.0
            System.out.println((i+1) + "번 학생의 총점: " + total+ ", 평균: " + average);
        }
    }

 

- 0,1,2,3 인덱스 총 4명 반복문으로 돌리기

- 과목 3개는  0,1,2 인덱스 총 3개로 돌리기

- 각 i, j로 인덱스 선언하여 행과 열에 알맞게 들어가게 설정

- 평균값은 double이니까 과목 3개로 나눠서 평균을 내려면 3.0으로 기입

 


📋 학생 수로 입력하기

package array.ex;

import java.util.Scanner;

public class ArrayEx8 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("학생 수를 입력하세요:");
        int studentCount = scanner.nextInt();

        int[][] scores = new int[studentCount][3];
        String[] subjects = {"국어","영어","수학"};

        //입력
        for(int i=0; i<studentCount; i++){ // i = 행
            System.out.println((i+1) + "번 학생의 성적을 입력하세요:");
            for(int j=0; j<3; j++) { // j = 열
                System.out.println(subjects[j] + " 점수:");
                scores[i][j] = scanner.nextInt();
            }
        }

        //출력
        for(int i=0; i<studentCount; i++){
            int total = 0;
            for(int j=0; j <3; j++){
                total += scores[i][j];
            }
            double average = total / 3.0; //3과목이니께 3.0
            System.out.println((i+1) + "번 학생의 총점: " + total+ ", 평균: " + average);
        }
    }
}

 

- studentCount 선언