Kotlinlearncs.online LogoJava
Return to List

Test Writing: Game CSV Sum with Map

Created By: Geoffrey Challen
/ Version: 2020.10.0

Chuchu and Xyz are playing a game. But this time they've invited their friends!

They've written down their scores in a String like this:

Xyz, 10
Chuchu,5
Sheldon,6
Xyz, 20
Lulu,8
Xyz, 4

The winner of the game is the player with the most total points. For the game above, the winner is Xyz, since she scored 34 points to Chuchu's 5, Sheldon's 6, and Lulu's 8. Note that zero is a valid number of points to have scored and should not be treated separately.

Create a public class Question with a single public static method called winner that determines the winner of the game. It accepts a single String argument containing CSV records as shown above and should return a String containing the winner. If any two players earn the maximum score you should return "Tie".

A few notes. First, you'll want to use both split and trim, two of our familiar functions for working with String data. Second, while each line will contain a record, there may be extra whitespace surrounding each record. (The data was entered by happy animals.) Third, recall that you can use Integer.parseInt to convert a String to an int. Fourth, if the String passed is null or empty you should return null.

Finally, unlike the previous version of this problem Chuchu and Xyz are not the only players! They have many friends, some with strange names. So the participants will be different from game to game.

This is a great problem to solve using a map. Here's a solution approach:

  1. Parse the CSV and combine all the scores into a map, totaling the score for each player as you go
  2. Loop over the map to compute the maximum

You may need to examine the map documentation. But as a helpful note, the keySet Map function will return all of the keys in the map, which you can iterate over:

Test Design Challenge

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

  • Provide a public class named TestQuestion with a single non-private class 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 Java's assert method