package kr.s10.object.method;
public class StudentMain {
//멤버 변수
String name;
int korean;
int math;
int english;
//멤버 메서드
//총점 구하기
public int makeSum() {
return korean + math + english;
}
//평균 구하기
public int makeAvg() {
return makeSum() / 3;
}
//등급 구하기
public String makeGrade() {
String grade;
switch(makeAvg() / 10) {
case 10:
case 9: grade = "A";break;
case 8: grade = "B";break;
case 7: grade = "C";break;
case 6: grade = "D";break;
default: grade = "F";
}
return grade;
}
public static void main(String[] args) {
StudentMain student = new StudentMain();
student.name = "홍길동";
student.korean = 98;
student.math = 87;
student.english = 100;
System.out.println("이름: " + student.name);
System.out.println("국어 : " + student.korean);
System.out.println("수학 : " + student.math);
System.out.println("영어 : " + student.english);
System.out.println("총점 : " + student.makeSum());
System.out.println("평균 : " + student.makeAvg());
System.out.println("등급 : " + student.makeGrade());
}
}
총점과 평균에 대한 계산은 메인 영역에서 별도로 해주어야 했던 전과 달리, 이 프로그램에서는 메서드를 활용해 총점과 평균을 구할 예정이다. 또한, switch문을 함께 활용해 총점에 따른 등급도 구할 수 있다.
참고) 객체의 멤버 변수만을 활용해 성적 프로그램 만들기
객체의 멤버 변수로 학생의 이름, 과목 점수를 저장할 변수들만 선언한다.
총점을 구할 메서드를 선언한다. 반환값은 정수들의 합이므로 int, 인자를 외부에서 받을 필요 없이 멤버 변수를 활용해 값을 연산, 반환한다.
ex. public int makeSum() {return korean + math + english;}
위 과정을 통해 같은 클래스에 있는 멤버 변수는 메서드 내에서 호출해 사용할 수 있다는 것을 알 수 있다.
평균을 구할 메서드를 선언한다. 반환값은 int로 하고 총점을 과목수로 나누어준다.
ex. public int makeAvg() {return makeSum() / 3;}
→평균의 자료형이 실수가 아니므로 3.0으로 나누어줄 필요가 없다.
위 과정을 통해 메서드 내에서 다른 메서드를 호출해 사용할 수 있다는 것을 알 수 있다.
등급을 구하는 메서드를 선언한다. 등급을 저장할 문자열 변수를 선언하고, switch문을 통해 평균에 따른 경우의 수를 나누어준다. 그 후, 등급이 결정되면 반환한다.
메인 영역에서 StudentMain 객체를 선언 및 생성한다.
객체의 멤버 변수(하위 구성원)들에 접근해 값을 저장해준다.
멤버 변수를 호출할 때와 마찬가지로 멤버 메서드 역시 객체명.메서드명(인자) 형태로 호출해준다.
ex. System.out.println("등급 : " + student.makeGrade());