Hands

From CompSciWiki
Jump to: navigation, search

Back to the Case Studies homepage

Problem

You work at a video game company as a junior programmer and have been tasked with writing a program, in Java, to calculate the angle of the hands on a clock. This program will be used in an upcoming game that features a time limit on certain tasks. In order to test your program, you will prompt the "user" for the hour and minute count. Then, assuming 12:00 is at position 0, calculate and output the angle of both the hour and minute hand. In order to make the visual designer's job easier, your solution will have to return the hour hand to the 0 degree position at 12:00.

Here’s an example run of the program, using 9:29 as the time.

Hour: 9
Minute: 29
The hour hand is at 284.5 degrees and the minute hand is at 174.0 degrees.
Programmed by [put your name here]
*** End of Processing ***

Creating this program will require a number of steps:

  • Figure out how far the hour and minute hands travel every minute.
  • Create the formulas.
  • Figure out how to return 0 degrees for the hour hand at 12:00.

Part of the specifications requires the input and output to be echoed to System.out.

 

Hands

Clock casestudy.jpg

Solution

There are three steps to solving this question.

Step 1: Calculate How Fast the Hands Travel

We first need to calculate how far the hour and minute hands travel each minute. The minute hand is easier, so we will start with it.

The Minute Hand

The minute hand travels 90 degrees in 15 minutes, which gives:

90 degrees/15 minutes = 6 degrees/minute

The Hour Hand

The hour hand is a bit trickier. It travels the full 360 degrees in 12 hours, which gives us:

360 degrees/12 hours = 30 degrees every hour = 1 degree every 2 minutes

Step 2: Create the Formulas

Now we need to take the above information and create formulas we can use in our coding solution.

The Minute Hand

minuteDegree = minute * 6;

The Hour Hand

This solution requires both aspects of our calculations above: the fact that in one hour, the hour hand moves 30 degrees; and the fact that the hour hand moves one degree every two minutes.

hourDegree = (hour * 30) + (minute*0.5);

Step 3: Resetting the Hour Hand at 12:00

However, when hour is 12, the hourDegree will be 360 degrees or greater using the above solution. We need to add a way to reset the degree count back to 0. An easy way to do this is to use modulus.

hourDegree = ((hour * 30) + (minute*0.5)) % 360;

This is just one way to calculate the hourDegree. Another way would be to calculate hour % 12 so the hour value is reset to 0.

Code

Solution Code

Back to the Case Studies homepage