The task
The starter code stores how long someone worked on a project in two values: hours and minutes. The exercise is to print the same amount of time in seconds. One hour and two minutes, for example, add up to 3720 seconds.
Approach
The easiest way to avoid mistakes is to convert in stages, using the units that link hours, minutes and seconds: 1 hour is 60 minutes, and 1 minute is 60 seconds.
- Everything in minutes. Turn the hours into minutes and add the minutes you already have:
hours * 60 + minutes. For 13 hours and 47 minutes, this is 13 * 60 + 47 = 827 minutes. - Minutes into seconds. Multiply the whole total by 60: 827 * 60 = 49620 seconds.
Joining the stages gives one expression, (hours * 60 + minutes) * 60. The first step must be complete before the second one starts, which is the reason for the parentheses.
Step by step
- Multiply
hoursby 60 to get the minutes that the hours contain. - Add
minutes. Now you have the total number of minutes. - Put that sum in parentheses and multiply it by 60 to get seconds.
- Pass the whole expression to
println.
The solution in Scala
val hours: Int = 13
val minutes: Int = 47
println((hours * 60 + minutes) * 60)
The output is:
49620
Why the parentheses matter
Multiplication ranks above addition in Scala. Without parentheses, hours * 60 + minutes * 60 multiplies each part separately, and the result is wrong. With 13 and 47 it prints 3600, not 49620. The hours term was only converted to minutes, while the minutes term was converted to seconds, so the two parts are in different units.
There is another correct way to write the same calculation: convert each part into seconds first, then add them. One hour is 3600 seconds, so:
println(hours * 3600 + minutes * 60)
This prints 49620 as well, and it needs no parentheses, because both terms are already in seconds before they are added. Choose the version that is easiest for you to explain.
Edge cases and common mistakes
- Mixed units. Add two numbers only when they are in the same unit.
hours * 60 + minutes * 60does not meet that rule, as shown above. - Extra multiplication.
hours * 60 + minutes * 60 * 60turns the minutes into thousands of seconds. For the lesson's values it prints169980. - Zero values. If
hoursis 0, the formula still works. With 0 hours and 5 minutes it gives 300. With both values at 0 it gives 0. - Using the names. Write
hoursandminutesin the expression instead of 13 and 47, so the result follows the values. - Size. Both values are
Int, so the result is anInttoo. It would wrap around only beyond 2147483647 seconds, about 68 years, which is no concern for a work log.
Key takeaways
- Convert to a common unit before adding:
hours * 60 + minutesis the total in minutes. - Parentheses make the addition run before the final
* 60. hours * 3600 + minutes * 60is an equivalent form.
