아래의 성적처리예제를 객체지향적으로 작성한 예제입니다.
비교해 보세요.
class SungJuk2
{
public static void main(String[] args)
{
Student[] score = {
new Student(100, 100, 100),
new Student(20, 20, 20),
new Student(30, 30, 30),
new Student(40, 40, 40),
new Student(50, 50, 50)
};
int koreanTotal = 0;
int englishTotal = 0;
int mathTotal = 0;
//과목별 총점을 얻는다.
for(int i=0; i < score.length; i++) {
koreanTotal += score[i].korean;
englishTotal += score[i].english;
mathTotal += score[i].math;
}
System.out.println("번호 국어 영어 수학 총점 평균 ");
System.out.println("==========================");
for(int i=0; i < score.length; i++) {
System.out.println(" " + (i + 1) + " " + score[i]);
}
System.out.println("=============================");
System.out.println("총점:" + koreanTotal + " " +englishTotal +" " +mathTotal);
}
}
class Student {
int korean=0;
int english=0;
int math=0;
Student(int korean, int english, int math) {
this.korean = korean;
this.english = english;
this.math = math;
}
// 학생의 총점을 반환한다.
int getTotal() {
return korean + english + math;
}
// 학생의 평균을 반환한다. 소수점아래값을 구하기 위해서 3.0으로 나눈다.
double getAverage() {
return getTotal() / 3.0;
}
// Object클래스의 toString()메서드를 오버라이딩(Overriding)한다.
public String toString() {
return korean + " " + english + " " + math + " " + getTotal() + " " + getAverage();
}
}
/*
번호 국어 영어 수학 총점 평균
=============================
1 100 100 100 300 100.0
2 20 20 20 60 20.0
3 30 30 30 90 30.0
4 40 40 40 120 40.0
5 50 50 50 150 50.0
=============================
총점:240 240 240
*/
비교해 보세요.
class SungJuk2
{
public static void main(String[] args)
{
Student[] score = {
new Student(100, 100, 100),
new Student(20, 20, 20),
new Student(30, 30, 30),
new Student(40, 40, 40),
new Student(50, 50, 50)
};
int koreanTotal = 0;
int englishTotal = 0;
int mathTotal = 0;
//과목별 총점을 얻는다.
for(int i=0; i < score.length; i++) {
koreanTotal += score[i].korean;
englishTotal += score[i].english;
mathTotal += score[i].math;
}
System.out.println("번호 국어 영어 수학 총점 평균 ");
System.out.println("==========================");
for(int i=0; i < score.length; i++) {
System.out.println(" " + (i + 1) + " " + score[i]);
}
System.out.println("=============================");
System.out.println("총점:" + koreanTotal + " " +englishTotal +" " +mathTotal);
}
}
class Student {
int korean=0;
int english=0;
int math=0;
Student(int korean, int english, int math) {
this.korean = korean;
this.english = english;
this.math = math;
}
// 학생의 총점을 반환한다.
int getTotal() {
return korean + english + math;
}
// 학생의 평균을 반환한다. 소수점아래값을 구하기 위해서 3.0으로 나눈다.
double getAverage() {
return getTotal() / 3.0;
}
// Object클래스의 toString()메서드를 오버라이딩(Overriding)한다.
public String toString() {
return korean + " " + english + " " + math + " " + getTotal() + " " + getAverage();
}
}
/*
번호 국어 영어 수학 총점 평균
=============================
1 100 100 100 300 100.0
2 20 20 20 60 20.0
3 30 30 30 90 30.0
4 40 40 40 120 40.0
5 50 50 50 150 50.0
=============================
총점:240 240 240
*/
[출처] 성적관리2 - 클래스를 이용한 총점, 평균 계산 |작성자 젊음이여