[ java ] 배열 응용 프로그램(ArrayList 배열 객체) 만들기

JooKit 주킷 2020. 12. 18. 23:56
목차 접기
728x90
반응형

ArrayList 객체 배열 사용법

package StudentArrayList;

import java.util.ArrayList;

public class Student {

    private String name;
    private int studentID;
    private ArrayList<Subject> subjects;

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

    public String getName() {
        return name;
    }

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

    public int getStudentID() {
        return studentID;
    }

    public void setStudentID(int studentID) {
        this.studentID = studentID;
    }

    public ArrayList<Subject> getSubjects() {
        return subjects;
    }

    public void setSubjects(ArrayList<Subject> subjects) {
        this.subjects = subjects;
    }

    public void addSubject(String name, int subjectScore) {
        Subject subject = new Subject();
        subject.setName(name);
        subject.setSubjectScore(subjectScore);
        subjects.add(subject);
    }

    public void showStudentInfo() {
        int total = 0;

        for ( Subject subject : subjects ) {
            total += subject.getSubjectScore();
            System.out.println("학생 " + name + "의 " + subject.getName() + " 과목 성적은 " + subject.getSubjectScore() + " 입니다.");
        }
        System.out.println("학생 " + name + "의 총점은 " + total + "점 입니다.");
    }



}

package StudentArrayList;

public class Subject {

    private String name;
    private int subjectScore;


    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSubjectScore() {
        return subjectScore;
    }
    public void setSubjectScore(int subjectScore) {
        this.subjectScore = subjectScore;
    }


}


package StudentArrayList;

public class Main {
    public static void main(String[] args ) {

        Student studentHong = new Student("홍길동", 1001);
        studentHong.addSubject("과학", 80);
        studentHong.addSubject("사회", 40);
        studentHong.addSubject("수학", 100);
        studentHong.addSubject("영어", 50);

        Student studentKim = new Student("김길순", 1002);
        studentKim.addSubject("과학", 70);
        studentKim.addSubject("수학", 20);
        studentKim.addSubject("국어", 100);

        studentHong.showStudentInfo();
        System.out.println("===========================");
        studentKim.showStudentInfo();


    }
}


728x90
반응형
LIST