Hacker Rank - Day 14 : Scope
Solution In Java 8:
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 String calculate(){
int sum = 0;
for(int i = 0; i < testScores.length ; i++){
sum = sum + testScores[i];
}
int avg = sum / testScores.length;
if(avg >= 90 && avg <= 100)
return "O";
else if(avg >= 80 && avg < 90)
return "A";
else if(avg >= 70 && avg < 80)
return "E";
else if(avg >= 55 && avg < 70)
return "P";
else if(avg >= 40 && avg < 55)
return "D";
else
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() );
}
}
Solution In Python 3:
class Person:
def __init__(self, firstName, lastName, idNumber):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNumber
def printPerson(self):
print("Name:", self.lastName + ",", self.firstName)
print("ID:", self.idNumber)
class Student(Person):
def __init__(self,firstName,lastName,ids,testScores):
super().__init__(firstName,lastName,ids)
self.testScores = testScores
def calculate(self):
total = 0
for testScore in self.testScores:
total += testScore
avg = total / len(self.testScores)
if 90 <= avg <= 100:
return 'O'
if 80 <= avg < 90:
return 'E'
if 70 <= avg < 80:
return 'A'
if 55 <= avg < 70:
return 'P'
if 40 <= avg < 55:
return 'D'
return 'T'
line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
numScores = int(input()) # not needed for Python
scores = list( map(int, input().split()) )
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print("Grade:", s.calculate())
Exception in thread "main" java.lang.NullPointerException
ReplyDeleteat Student.calculate(Solution.java:xx)
at Solution.main(Solution.java:xx)