Programming Language/Java

매개변수 생성자를 이용해 학생 성적 출력하기

Ma_Sand 2022. 3. 2. 21:02
반응형

단, 총점과 평균은 직접 설정하지 않는다. 그리고 점수를 한 개만 설정하면 국어점수로 간주하며, 점수를 두 개 설정하면 각각 국어 점수와 영어 점수로 간주한다.

 

public class Grade {

    // 필드
    private String name;  // 학생 이름
    private int kor;  // 국어 점수
    private int eng;  // 영어 점수
    private int math;  // 수학 점수
    private int total;  // 총점
    private double avg;  // 평균
    
    // 생성자
    public Grade() {}  // 기본 생성자
    // 매개변수로 초기화
    // 합계와 평균을 직접 설정하지 말라는 것은 매개변수에 넣지 말라는 뜻이다.
    public Grade(String name, int kor, int eng, int math) {  // 매개변수 생성자
        this.name = name;
        this.kor = kor;
        this.eng = eng;
        this.math = math;
        this.total = (kor + eng + math);
        this.avg = (double) total / 3; 
    }
    // 점수를 한 개만 설정하면 국어 점수로 간주한다.
    public Grade(String name, int kor) {
        this.name = name;
        this.kor = kor;
    }
    // 점수를 두 개로 설정하면 국어 점수와 영어 점수로 간주한다.
    public Grade(String name, int kor, int eng) {
        this(name, kor, eng, 0);
        // 이 this()문은 클래스 안에 있는 생성자 구문을 호출하는 것, 반드시 첫째 줄에 선언.
        // math는 아직 초기화되지 않아 기본값 0으로 넣는다.
    }
    
    // 메소드
    public void student() {
        System.out.println("| 이름 | 국어점수 | 영어점수 | 수학점수 | 총점 | 평균 |");
        System.out.println("| --- | ----- | ----- | ----- | --- | --- |");
        System.out.printf("| %s | %d | %d | %d | %d | %.2f |", name, kor, eng, math, total, avg);
    }  // %.2f: 소수점 두 자리까지 출력
}


// 값 입력 클래스
public class GradeTest {
    public static void main(String[] args) {
        Grade G = new Grade("홍길동", 80, 90, 96);
        G.student();
    }
}

▼실행결과

| 이름 | 국어점수 | 영어점수 | 수학점수 | 총점 | 평균 |
| --- | ----- | ----- | ----- | --- | --- |
| 홍길동 | 80 | 90 | 96 | 266 | 88.67 |
반응형