Write a method called getGrade that accepts an integer representing a student’s grade in a course and returns that student’s numerical course grade. The grade can be between 0.0 (failing) and 4.0 (perfect). Assume that scores are in the range of 0 to 100 and that grades are based on the following scale:
For an added challenge, make your method throw an IllegalArgumentException if the user passes a grade lower than 0 or higher than 100.
Program:
public class Ch04Ex12
{
public static void main(String[] args)
{
System.out.println("getGrade(26): " + getGrade(26));
System.out.println("getGrade(62): " + getGrade(62));
System.out.println("getGrade(97): " + getGrade(77));
System.out.println("getGrade(97): " + getGrade(97));
}
public static double getGrade(int score)
{
if (score < 0 || score > 100)
{
throw new IllegalArgumentException("Invalid score.");
}
if (score < 60)
{
return 0.0;
}
else if (score <= 62)
{
return 0.7;
}
else if (score <= 94)
{
double grade = 0.8;
for (int i = 63; i < score; i++)
{
grade += 0.1;
}
return Math.round(grade * 10.0) / 10.0;
}
else
{
return 4.0;
}
}
}
Output:
getGrade(26): 0.0
getGrade(62): 0.7
getGrade(97): 2.2
getGrade(97): 4.0