Find angle between hour hand and minute hand in Java

In this tutorial, we are given a time in hh : mm format. Our aim is to find the shorter angle formed between the minute hand and the hour hand of the analog clock in Java.

Hour-hand

  • The hour hand sweeps 360-degree angle in 12hrs in a 12-hr analog clock.
  • In 1-hr it covers a 360/12-degree angle i.e., a 30-degree angle.
  • In 1-hr, a minute covers 360/(12*60) degree angle. That is the 0.5-degree angle.

Minute-hand

  • The minute hand sweeps a 360-degree angle angle in 1-hr or 60 minutes.
  • It covers 360/60 = 6-degree angle in a minute.

Our final will be the absolute difference between the angle covered by the minute hand and the hour hand.

So, if the time given is 5:30, this implies:

The angle covered by an hour hand : 5*30 + 30*0.5 = 165-degree

The angle covered by a minute hand : 30*6 = 180-degree

Therefore, the angle between  an hour hand and a minute hand is 180-165-degree = 15-degree.

Now, if the angle is greater than 180-degree, subtract it form 360-degree to get an answer.

Given below is the implementation of the above logic. The code is the implementation of what is explained above. First, we find an angle covered by an hour hand in degrees. Then, we find an angle covered by a minute hand in degrees. We subtract to obtain the answer. Since our aim is to find the shorter angle, now if angle>180-degree. Then the answer will be 360-angle.

Java program to calculate the angle between hour hand and minute hand

import java.io.*;
import java.util.* ;
public class codespeedy {
    static Scanner scn = new Scanner(System.in);
  public static void main (String[] args) {
    int hr = scn.nextInt();
    int min = scn.nextInt();
    int ans = findAngle(hr,min);
    System.out.println(ans);
  }  
   static int findAngle(int hr, int min){
      
      // find angle covered by hour hand.
      
      int hour = (hr*30) + (int)(min*0.5);
      
      // find angle covered by minute hand
      int minutes =  min*(6) ;
      
      //substract and take absolute value to obtain answer
      
      int ans = Math.abs(hour-minutes);
      
      if(ans>180){
          return 360-ans;
      }
      return ans ;      
  }
}

The input provided for the above code is :

6
0

The output for the above code is :

180

Leave a Reply

Your email address will not be published. Required fields are marked *