Codewars Kata: Looking for a benefactor 2 of 2
When we last left our hero, he just discovered he’d made a grave error in his codewar submission…
My solution worked perfectly on my laptop. It compiled with no errors, and satisfied all the test cases I came up with. However, this didn’t meet the requirements of the challenge.
For starters, the only requirement was to write the method that returns the donation amount needed. Similar to mine, it accepted an array and the new target average. However, they were of type double! Logically, since this is an exercise dealing with currency, the donation amounts should be type double. Not to mention it adds precision to the solution if it can accept any dollar amount. Data types should always be chosen with intent.
That being said, instead of using IntStream, I used the DoubleStream class. It has the sum method same as IntStream and translating my code was seamless.
After calculating the donation amount needed, the program is supposed to round to the next whole number. Even though the array holds values of type double, the result needs to be a whole number. Even when I used to wait tables, I would rather round up when giving someone change. It makes things easier. To accomplish this, I used the ceiling method of the Math class. It returns its argument rounded up.
The last requirement was a new one to me. The program should return an IllegalArgumentException if the donation amount needed is less than zero. In other words, the program should throw an exception if the current average is greater than the target average. It took some research to understand how to “throw” an exception. In the end, I imported the IllegalArgumentException class and implemented it in the code.
This was a lot of fun! Especially using exceptions for input validation. I’ll definitely use that again in future programs. Onward to the next challenge!