JAVA

ArrayList 사용한 배열 응용 프로그램

seungmin576 2024. 12. 19. 15:11

ArrayList를 사용해 학생 성적 출력 프로그램을 구현해 본다.

이 프로그램은 Student 클래스와 Subject 클래스를 사용한다.

만약 어떤 학생이 10과목 수강한다면 Subject 클래스형을 자료형으로 선언한 변수가 10개 필요할 것이다.

또 어떤 학생은 3과목을, 어떤 학생은 5과목을 수강할 수도 있다.

따라서 이러한 경우에는 배열을 사용하여 프로그램을 구현하는 것이 좋다.

Subject 클래스는 참조 자료형이므로 ArrayList를 활용해서 구현해본다.

 

  • 예제 시나리오

1001학번의 Lee와 1002학번 Kim, 두 학생이 있다.

Lee 학생은 2과목을 수강한다.

국어 점수가 100점, 수학 점수가 50점이다.

Kim 학생은 3과목을 수강한다.

국어 점수가 70점, 수학 점수가 85점, 영어 점수가 100점이다.

Student 클래스와 Subject 클래스를 생성한 후 두 학생의 과목 성적과 총점을 각각 출력한다.

package arraylist;

import java.util.ArrayList;

public class Student {
    int studentID;
    String studentName;
    ArrayList<Subject> subjectList;

    public Student(int id, String name){
        studentID = id;
        this.studentName = name;
        subjectList = new ArrayList<Subject>();
    }

    public void addSubject(String name, int score){
        Subject subject = new Subject();
        subject.setName(name);
        subject.setScore(score);
        subjectList.add(subject);
    }

    public void showInfo(){
        int total = 0;
        for(Subject s : subjectList){
            total += s.getScorePoint();
            System.out.println("학생 " + studentName + "의 " + s.getName() + " 과목 성적은 " + s.getScorePoint() + "입니다.");
        }
        System.out.println("학생 " + studentName + "의 총점은 " + total + " 입니다.");
    }
}

한 학생이 수강하는 과목은 여러 개 있을 수 있으므로, Subject 클래스형으로 ArrayList를 생성한다.

subjectList는 학생이 수강하는 과목을 저장할 배열이다.

학생의 수강 과목을 하나씩 추가하기 위해 addSubject() 메서드를 만든다.

매개변수로 넘어온 과목 이름과 점수를 가지고 Subject 클래스를 생성하고, 생성한 인스턴스는 subjectList에 추가한다.

그러면 이 학생의 수강 과목 정보는 subjectList에 저장된다.

showStudentInfo() 메서드에서는 각 과목의 성적과 총점을 출력한다.

향상된 for문을 사용하여 subjectList 배열 내용을 출력할 수 있다.


Subject 클래스 구현

  • 과목 정보를 담고 있는 Subject 클래스 예제
package arraylist;

public class Subject {
    private String name;
    private int scorePoint;

    public String getName(){
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScorePoint() {
        return scorePoint;
    }

    public void setScorePoint(int scorePoint) {
        this.scorePoint = scorePoint;
    }
}

Subject 클래스의 멤버 변수는 과목 이름과 성적 두 가지이다.

멤버 변수의 get(), set() 메서드를 구현했다.


테스트 클래스 구현

학생 두 명을 생성하고 각 학생의 과목별 성적과 총점을 출력

package arraylist;

public class StudentTest {
    public static void main(String[] args){
        Student studentLee = new Student(1001, "Lee");
        studentLee.addSubject("국어", 100);
        studentLee.addSubject("수학", 50);

        Student studentKim = new Student(1002, "Kim");
        studentKim.addSubject("국어", 70);
        studentKim.addSubject("수학", 85);
        studentKim.addSubject("영어", 100);

        studentLee.showInfo();
        System.out.println("==============");
        studentKim.showInfo();
    }
}

5행에서 studentLee를 생성한다.

학생 ID는 1001, 이름은 Lee이다.

studentLee의 addSubject() 메서드를 호출하여 학생 Lee가 수강 중인 국어, 수학 과목을 studentLee의 subjectList에 추가한다.

마찬가지로 학생 ID가 1002, 이름은 Kim인 studentKim을 9행에서 생성하고 이번에는 국어, 수학, 영어 3과목을 addSubject() 메서드를 사용하여 추가한다.

shoStudentInfo() 메서드를 호출하여 각 학생의 과목별 성적과 총점을 출력한다.

'JAVA' 카테고리의 다른 글

상속에서 클래스 생성과 형 변환, super()  (0) 2024.12.19
상속  (1) 2024.12.19
ArrayList  (0) 2024.12.19
다차원 배열  (0) 2024.12.18
배열, 향상된 for문  (1) 2024.12.18