Hands
Back to the Case Studies homepage
ProblemWrite 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:
Part of the specifications requires the input and output to be echoed to System.out. |
Hands | |
---|---|---|
SolutionThere are three steps to solving this question.
Calculate How Fast the Hands TravelWe 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 HandThe Minute Hand travels 90 degrees in 15 minutes, which gives: 90 degrees/15 minutes = 6 degrees/minute The Hour HandThe 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 FormulasNow we need to take the above information and create formulas we can use in our coding solution. The Minute HandminuteDegree = minute * 6; The Hour HandThis 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:00However, 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 |