thorax232

Time Angles

Mar 12th, 2014
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. /* Write a program to find the minimum angle between two hands on a 24 hour
  2.  * clock. For instance, the angle at 6:00 is 90 degrees and the angle at 18:00
  3.  * is also 90 degrees.
  4.  */
  5. import java.util.Scanner;
  6. import java.text.DecimalFormat;
  7.  
  8. public class TimeAngles {
  9.     public static void main(String[] args) {
  10.         Scanner input = new Scanner(System.in);
  11.         DecimalFormat df = new DecimalFormat();
  12.        
  13.         System.out.print("Enter time (e.g. 6:17, 5:40): ");
  14.         String userIn = input.nextLine();
  15.        
  16.         // Get two integers from time.
  17.         String[] numStr = userIn.split(":");
  18.         int[] times = new int[numStr.length];
  19.        
  20.         for(int i = 0; i < numStr.length; i++) {
  21.             times[i] = Integer.parseInt(numStr[i]);
  22.         }
  23.        
  24.         // Calculate angle between two hands.
  25.         double angle = angleCalc(times[0], times[1]);
  26.        
  27.         System.out.println(df.format(angle) + " degrees");
  28.     }
  29.    
  30.     static double angleCalc(double hour, double minute) {
  31.         // Calculate angle with (Hours relative to degrees) -
  32.         //      (Minutes relative to degrees)
  33.         // Minute / 60 converts to decimal hour
  34.        
  35.         double dph = 360 / 24; // Degrees per hour
  36.         double minOnFace = minute / 5; // Where minute hand is at on clock face
  37.        
  38.         double hourAngle = hour * dph;
  39.         double minAngle = minOnFace * dph;
  40.         double angle = hourAngle - minAngle;
  41.        
  42.         // If minute > hour, will return negative
  43.         // Make sure number is positive.
  44.         if(angle < 0) {
  45.             angle = Math.abs(angle);
  46.         }
  47.        
  48.         // Looking for smallest distance of two.
  49.         if(angle > 180) {
  50.             return 360 - angle;
  51.         } else {
  52.             return angle;
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment