Kotlinlearncs.online LogoJava
Return to List

Test Writing: Calculate GPA

Created By: Rohith Sanjay
/ Version: 2025.1.1

Write a method called gpaCalculator which calculates the GPA and returns the GPA as a Double. This method takes in 2 parameters. Both of the parameters are Maps. The first parameter is a grades map Map<String, Double>, which maps a course name (key) to the grade (value, double between 0.0 and 4.0 inclusive). The second parameter is a credits map Map<String, Int>, which maps a course name (key) to the credit hour amount (integer between 0 and 4 inclusive). To calculate the GPA, there are two steps:

  1. You must first take the sum of each grade-credit product only for courses that the student has taken (the ones used in the grades map). For example, the grade-credit product for a class named "CS 124" is the result of multiplying the grade value of that class (found from the first map) by the credit value of that class (found from the second map). Do this for all classes the student has taken.
  2. Then, after you obtain the sum of all grade-credit products, divide this result by the total number of credit hours the student has taken. Return this final output as the GPA.

Some important notes:

  1. ALL the courses the student has taken are in the grades map. The credits map may include extra courses the student has NOT taken, which should be disregarded (DON'T include extra courses in the GPA). Assume that if a course is in the grades map, it will also be found in the courses map (but not necessarily the other way around).
  2. If the student has taken NO credit hours (or NO courses), return 0, to avoid divide-by-zero errors.

As usual, maps are built-in to Kotlin and available for you to use to solve this problem.

Test Design Challenge

You're challenge is to write tests for this problem described above.

  • Provide a method named test that accepts no arguments and does not return a value.
  • If the implementation of the class described above is incorrect, your test method should throw an exception.
  • If it is correct, do not throw an exception.
  • You may want to use Kotlin's assert or check methods
Report a Problem

Attribution must link to this page: https://www.learncs.online/testtesting/kotlin/calculate-gpa/[email protected]