[그린컴퓨터] Server/JAVA(객체 지향 프로그래밍)

배열 응용 프로그램 { Student 클래스 구현하기, 테스트 클래스 구현 }

Ben의 프로그램 2023. 5. 25. 22:47
728x90

ArrayList 를 쓰면 좋은 상황?

  • 지금까지 배운 ArrayList 를 사용해 학생 성적 출력 프로그램을 구현해 보겠습니다. 
  • 이 프로그램은 Student 클래스와 Subject 클래스를 사용합니다. 
  • 만약 어떤 학생이 10과목을 수강한다면 Subject 클래스형을 자료형으로 선언한 변수가 10개 필요할 것입니다. 
  • 어떤 학생은 3 과목을 수강할 수도 있고, 어떤 학생은 5과목을 수강할 수도 있습니다.
  • 따라서 이러한 경우에는 배열을 사용하여 프로그램을 구현하는 것이 좋습니다. 

Student 클래스 구현하기

  • 2 명의 학생을 만들고 두 학생의 과목 성적과 총점을 각각 출력해 봅시다. 
package arraylist;
import java.util.ArrayList;

public class Student {
	int studentID;
	String studentName;
	ArrayList<Subject> subjectList;   // ArrayList 선언하기
	
	public Student(int studentID, String studentName, ArrayList<Subject> subjectList) {
		super();
		this.studentID = studentID;
		this.studentName = studentName;
		this.subjectList = new ArrayList<Subject>();   // ArrayList 생성하기
	}
	
	public void addSubject(String name, int score) {
		Subject subject = new Subject();
		subject.setName(name);
		subject.setScorePoint(score);
		subjectList.add(subject);
	}
	
	public void showStudentInfo() {
		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 메서드를 만듭니다. 
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 클래스를 구현했습니다. 

Test 클래스 구현

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.showStudentInfo();
		System.out.println("===============");
		studentKim.showStudentInfo();
		
	}

}
  • Test 클래스를 구현했습니다.