Java/JAVA의 정석_문제풀이

[6-3~5]연습문제 - 메서드/생성자

Jenny_yoon 2022. 11. 4. 17:51
728x90
반응형

 

[6-3] 다음과 같은 멤버변수를 갖는 Student클래스를 정의하시오.

 

[6-4] 문제6-3에서 정의한 Student클래스에 다음과 같이 정의된 두 개의 메서드 getTotal()과 getAverage()를 추가하시오.

 


 

풀이

1) Student 클래스 생성

class Student{
	String name;
	int ban;
	int no;
	int kor;
	int eng;
	int math;
}

2) getTotal 메서드 생성

//	int getTotal(int kor, int eng, int math) { 인자의 값이 없으므로 인자 삭제 ! otherwise 오류발생 
	int getTotal() {
		int result = kor + eng + math;
		return result;
	}

     or (아래가 더 좋은 코드)

	int getTotal() {
		return kor + eng + math;
	}

3) getAverage 메서드 생성

	float getAverage() {
		float result = (int)(getTotal()/3f * 10 + 0.5f)/10f;
		return result;
	}

     or (아래가 더 좋은 코드)

	float getAverage() {
		return (int)(getTotal()/3f * 10 + 0.5f)/10f;
	}

     return 값(평균을 소수점 둘째자리에서 반올림 하기) 해설 :

정답
class Student1{
	String name;
	int ban;
	int no;
	int kor;
	int eng;
	int math;

	int getTotal() {
		return kor + eng + math;
	}
	float getAverage() {
		return (int)(getTotal()/3f * 10 + 0.5f)/10f;
	}
}
public class Ex6_4 {
	public static void main(String[] args) {
Student1 s = new Student1();
s.name = "홍길동";
s.ban = 1;
s.no = 1;
s.kor = 100;
s.eng = 60;
s.math = 76;

System.out.println("이름:"+s.name);
System.out.println("총점:"+s.getTotal());
System.out.println("평균:"+s.getAverage());
	}
}

 


 

[6-5] 다음과 같은 실행결과를 얻도록 Student클래스에 생성자와 info()를 추가하시오.


 

풀이

1) Student 클래스 생성

class Student3{
	String name;
	int ban;
	int no;
	int kor;
	int eng;
	int math;
}

2) Student 생성자 생성

		Student3 (String name, int ban, int no, int kor, int eng, int math){
		this.name = name;
		this.ban = ban;
		this.no = no;
		this.kor =kor;
		this.eng = eng;
		this.math = math;
		}

3) getTotal 메서드 생성

	int getTotal() {
		return kor+eng+math;
	}

4) getAverage 메서드 생성

	float getAverage() {
		return (int)(getTotal()/3f * 10 +0.5f)/10f;
	}

5) info 메서드 생성

: info메서드를 구성하는 getTotal메서드, getAverage메서드, Student생성자를 모두 생성/구현 완료 했으니,

아래 info()의 실행결과물을 보고 info메서드를 어떻게 작성하면 될지 구현하기. 

	public String info() {
		return name +","+
				ban +","+
				no  +","+
				kor +","+
				eng +","+
				math +","+
				getTotal() +","+
				getAverage();
	}

 

정답
package pkg1;

class Student3{
	String name;
	int ban;
	int no;
	int kor;
	int eng;
	int math;
	
	Student3 (String name, int ban, int no, int kor, int eng, int math){
	this.name = name;
	this.ban = ban;
	this.no = no;
	this.kor =kor;
	this.eng = eng;
	this.math = math;
	}
    
	int getTotal() {
		return kor+eng+math;
	}
	float getAverage() {
		return (int)(getTotal()/3f * 10 +0.5f)/10f;
	}
	public String info() {
		return name +","+
				ban +","+
				no  +","+
				kor +","+
				eng +","+
				math +","+
				getTotal() +","+
				getAverage();
	}
}
public class Ex6_5 {
	public static void main(String[] args) {
		Student3 s = new Student3("홍길동",1,1,100,60,76);
	
		System.out.println(s.info());
	}
}
728x90
반응형