Hands

From CompSciWiki
Revision as of 12:27, 31 March 2011 by Glen (Talk | contribs)

Jump to: navigation, search

Back to the Case Studies homepage

Problem

Write a complete Java program that will ask the user for the hour and minute of an analog clock. Then, assuming 12:00 is at position 0, calculate and output the angle of both the hour and minute hand. An additional part of the question is to come up with a solution that returns the hour hand to the 0 degree position at 12:00.

Here’s an example run of the program, using the time shown in the picture.

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 ***

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

Wiki start01.jpg

Solution

There are three steps to solving this question.


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 or 1 degree every 2 minutes

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);

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