source: https://www.hackerrank.com/challenges/30-inheritance?h_r=next-challenge&h_v=zen
Student的创造方法,这样子写:
Student(String firstName, String lastName, int id, int[] testScores) {
super(firstName, lastName, id);
this.testScores = testScores;
}
是可以的,
但,若这样子写:
Student(String firstName, String lastName, int id, int[] testScores) {
this.firstName = firstName;
this.lastName = lastName;
this.idNumber = id;
this.testScores = testScores;
}
就会报错:如下:
Solution.java:26: error: constructor Person in class Person cannot be applied to given types;
Student(String firstName, String lastName, int id, int[] testScores) {
^
required: String,String,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
import java.util.*;
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;
Student(String firstName, String lastName, int id, int[] testScores) {
super(firstName, lastName, id);
this.testScores = testScores;
}
public char calculate(){
int avg = Arrays.stream(testScores).sum()/testScores.length;
if (avg >= 90) return 'O';
if (avg >= 80) return 'E';
if (avg >= 70) return 'A';
if (avg >= 55) return 'P';
if (avg >= 40) return 'D';
return 'T';
}
}
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() );
}
}