I need find the average grade of all the students in the university and create custom exception while finding the average in the Arrays.asList
. Exception should be thrown if int warCraftGrade
< 0 or int warCraftGrade
> 10. I have the following code:
public class Student {
String name;
public final int warCraftGrade;
public Student(String name, int warCraftGrade) {
this.name = name;
this.warCraftGrade = warCraftGrade;
}
public String getName() {
return name;
}
public int getWarCraftGrade() {
return warCraftGrade;
}
I have the list of students:
static List<Student> students = Arrays.asList(
new Student("Geoffrey Baratheon", 8),
new Student("Barristan Selmy", 6) //and so on
);
And the method of getting the average:
double warCraftAverageGrade = students.stream()
.mapToDouble(Student::getWarCraftGrade)
.average()
.getAsDouble();
I created special exception class:
public class GradeException extends Exception{
public GradeException() {
}
public GradeException(String message) {
super(message);
}
public GradeException(String message, Throwable cause) {
super(message, cause);
}
And the class to define the exception method:
public class StudentActions {
public static void range (Student student) throws GradeException {
if (student.warCraftGrade < 0 || student.warCraftGrade > 10) {
throw new GradeException("Wrong grade");
}
}
}
The problem occurs when I'm trying to use StudentActions.range()
method:
public static void main(String[] args) {
try {
StudentActions.range();
double warCraftAverageGrade = students.stream()
.mapToDouble(Student::getWarCraftGrade)
.average()
.getAsDouble();
System.out.println("Average grade in WarCraft for the entire university = " + warCraftAverageGrade);
} catch (GradeException e) {
System.out.println("Grade is out of range (0-10)");
}
What is the correct solution to form the custom exception in such a case? The correct code must throw GradeException
if the grade, for example, is negative:
//new Student("Jorah Mormont", -8)
Thank you in advance!