티스토리 뷰

성적을 멤버변수로 입력받고, 성적의 총점, 평균 등급을 계산해 출력하는 Class 를 구현해 보겠습니다.

 

실습을 위한 class 구성은 다음과 같습니다.

package com.score;

public class MTest {

	public static void main(String[] args) {
		Score lee = new Score();
		lee.setName("쟌쥰");
		lee.setKor(100);
		lee.setEng(23);
		lee.setMath(75);
		
		Score hong = new Score("홍길동", 58, 90, 17);
		
		//toString() 을 호출하지 않아도 출력은 toString() 메서드의 return 값 으로 나옴
		System.out.println(lee.toString());
		System.out.println(hong);
		
	}
}

위의 class diagram 과 main 함수의 호출을 통해 콘솔창에 출력되도록 클래스를 구성해 보겠습니다.

package com.score;

public class Score {

	private String name;
	private int kor;
	private int eng;
	private int math;

	public Score() {

	}

	public Score(String name, int kor, int eng, int math) {
		super();
		this.name = name;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}

	public String getName() {
		return name;
	}

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

	public int getKor() {
		return kor;
	}

	public void setKor(int kor) {
		this.kor = kor;
	}

	public int getEng() {
		return eng;
	}

	public void setEng(int eng) {
		this.eng = eng;
	}

	public int getMath() {
		return math;
	}

	public void setMath(int math) {
		this.math = math;
	}

	public int getSum() {
		return this.getKor() + this.getEng() + this.getMath();
	}

	public double getAvg() {
		return (double) getSum() / 3.0;
	}

	public String getGrade() {

		switch ((int) getAvg() / 10) {
		case 9:
			return "A";
		case 8:
			return "B";
		case 7:
			return "C";
		case 6:
			return "D";
		default:
			return "F";
		}
	}

	//Object.class의 toString 을 오버라이딩
	@Override
	public String toString() {
		return "이름 : " + name + " 국어 : " + kor + " 영어 : " + eng + " 수학 : " + math + " 총점 : " + getSum() + " 평균 : "
				+ getAvg() + " 등급 : " + getGrade();
	}
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함