w3resource

Java: Find the angle between the hour and minute hands


Angle Between Clock Hands

Write a Java program to find the angle between the hour and minute hands.

Sample Solution:

Java Code:

import java.util.*;
public class solution {
  static int calcAngle(double ha, double ma) {
    if (ha == 12)
      ha = 0;
    if (ma == 60)
      ma = 0;
    int hour_angle = (int)(0.5 * (ha * 60 + ma));
    int minute_angle = (int)(6 * ma);

    int angle = Math.abs(hour_angle - minute_angle);
    angle = Math.min(360 - angle, angle);
    return angle;
  }

  public static void main(String[] args)

  {
    Scanner scan = new Scanner(System.in);
    System.out.print("Input angles move by hour hand: ");
    int ha = scan.nextInt();
    System.out.print("Input angles move by minute hand: ");
    int ma = scan.nextInt();
    if (ha < 0 || ma < 0 || ha > 12 || ma > 60) {
      System.out.println("Wrong input..!");
    } else {
      System.out.println("Angle between hour and minute hands " + calcAngle(ha, ma) + " degree.");
    }
  }
}

Sample Output:

Input angles move by hour hand:  5
Input angles move by minute hand:  15
Angle between hour and minute hands 67 degree.

Flowchart:

Flowchart: Find the angle between the hour and minute hands.


For more Practice: Solve these Related Problems:

  • Write a Java program to calculate the angle between the hour and minute hands of a clock using a precise mathematical formula.
  • Write a Java program to compute the smaller angle between the clock hands and adjust for cases where the angle exceeds 180 degrees.
  • Write a Java program to determine the angle between the clock hands using modular arithmetic and compare the result with a simulation.
  • Write a Java program to find the time at which the angle between the clock hands is a given value using numerical methods.

Go to:


PREV : Excel Column from Number.
NEXT : Java Numbers Exercises Home.


Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.