스터디사이트 : https://www.hackerrank.com



JAVA Basic : 클래스 상속 , super메소드의 사용



※ 조건


Person클래스와, 이 클래스에서 파생된 Student 클래스 두 클래스가 있다.

Student 클래스는 Person 클래스를 상속받은 클래스이다.

class Student extends Person{

private int[] testScores;

   

}


Student 클래스의 생성자는 4개의 파라미터가 존재한다.

1. String firstName

2. String lastName

3. int id

4. int 배열 testScores


코딩 해야 하는 calculate() 메소드는...

Student 객체의 평균을 계산하고, 평균 점수별로 매겨진 등급을 리턴시킨다.

calculate()의 리턴타입은 char 이다.


입력되는 변수의 제약조건

firstName, lastName 의 길이는 4 ~ 10 자리

id 의 길이는 7자리

score, average의 범위는 0 ~ 100점


※ 주어진 코드

: 아래 표시된 영역 안에서만 코딩 할 것.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Person {
    protected String firstName;
    protected String lastName;
    protected int idNumber;
    
    // Constructor
    Person(String firstName, String lastName, int identification){
        this.firstName = firstName;
        this.lastName = lastName;
        this.idNumber = identification;
    }
    
    // Print person data
    public void printPerson(){
         System.out.println(
                "Name: " + lastName + ", " + firstName 
            +     "\nID: " + idNumber); 
    }
     
}
 
class Student extends Person{
    private int[] testScores;
    /* 여기에 코딩. */
}
 
 
class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String firstName = scan.next();
        String lastName = scan.next();
        int id = scan.nextInt();
        int numScores = scan.nextInt();
        int[] testScores = new int[numScores];
        for(int i = 0; i < numScores; i++){
            testScores[i] = scan.nextInt();
        }
        scan.close();
        
        Student s = new Student(firstName, lastName, id, testScores);
        s.printPerson();
        System.out.println("Grade: " + s.calculate() );
    }
}
cs



입력

Heraldo Memelli 8135627

2

100 80


출력

 Name: Memelli, Heraldo

 ID: 8135627

 Grade: O



디버깅

입력받는 순서는 보니까

firstName lastName id

numScores

testScores[0] testScores[1]

순이다.


코딩을 해야 할 부분은

calculate() 메소드 코딩하고,

Grade 변수를 계산해서 출력시키면 되겠다.


그런데 주어진 코딩 line 43에 보면 s.calculate() 메소드에 파라미터가 전혀 없는데.

무슨 수로 main메소드 안에 존재하는 입력변수를 집어넣어서 계산을 할 수 있다는건지.?


근데 이거는 나혼자만의 바보같은 생각이었다.

main메소드안에 버젓이 Student 생성자 중 네번째 파라미터가 점수입력변수였던 것을.. 나만몰랐던 말인가.



코딩연습 1

코딩하는 영역만 표시를 하겠다.

1차시도로 Person클래스를 상속받은 Student 클래스 안에서 생성자가 없길래 인자4개짜리 생성자를 만들었다.

그런데 이런 에러가 나온다.

error: constructor Person in class Person cannot be applied to given types;

class Student extends Person{

private int[] testScores;

  

  Student(String firstName, String lastName, int id, int[] testScores){

        this.testScores = testScores;

  }

}

결과 : 

error: constructor Person in class Person cannot be applied to given types;


코딩연습 2

이클립스의 위대함..

class Student extends Person{

private int[] testScores;

   

}

코딩영역에 위 코딩만 치니까 아래 에러메시지가 나온다.

" Implicit super constructor Person() is undefined for default constructor. Must define an explicit constructor "

그리고 줄표시란옆에 빨간 x박스 그림을 누르면 Eclipse에서 제안하는 조치방법들이 나오는데, 내 무릎을 치는 제안이 나온다..


super() 메소드를 써서 Person클래스에 있는 생성자를 불러오는 것이다.

이것은 Student 클래스가 Person클래스를 상속받았기 때문에 가능한 방법이다.

class Student extends Person{

Student(String firstName, String lastName, int identification) {

super(firstName, lastName, identification);

// TODO Auto-generated constructor stub

}

}

- 에러없음 -



코딩연습 & 결과


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
32
33
34
35
36
37
class Student extends Person{
    private int[] testScores;
    
    Student(String firstName, String lastName, int id, int[] testScores){
        super(firstName, lastName, id);
        this.testScores = testScores;
    }
    
    public String calculate(){
        int sum=0;
        int average = 0;
        String grade="";
         
        for(int i=0; i<testScores.length; i++){
            sum=sum+testScores[i];
        } //end for
        
        average = sum / testScores.length;
        
        if(average >=90 && average <=100){
            grade="O";
        }else if(average>=80 && average <90){
            grade="E";
        }else if(average>=70 && average <80){
            grade="A";
        }else if(average>=55 && average <70){
            grade="P";
        }else if(average>=40 && average <55){
            grade="D";
        }else if(average<40){
            grade="T";
        }else{
            grade="over 100 or sth is missing";
        }
        return grade;
    } //end calculate 
}
cs

결과 : 

 Name: Memelli, Heraldo

 ID: 8135627

 Grade: O



+ Recent posts