w3resource

Java: Find the angle between the hour and minute hands

Java Math Exercises: Exercise-30 with Solution

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.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Multiply two numbers using bitwise operators.
Next: Java Sorting Exercises Home.

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.