In order to get the angle between the minute and hour hand of an analog clock, we should be able to derive the below mentioned angle

  1. Minute hand angle.
  2. Hour hand angle.
  3. Difference between the minute and hour hand angle.

To arrive at these, we should first understand the fundamentals. Let us convert the units to similar stage so that we will be able to get the logic perfectly.

Formula to generate the angle of the hour hand:

Hour Angle=(h*60+m)*0.5


Formulae to generate the angle of the minute hand :

Minute Angle=m*6


The difference between the both will yield you the angle between the two hands :

Now lets proceed with writing the java code based on the above inputs



package org.karthikk.com;

import java.util.Scanner;

import org.apache.log4j.Logger;


public class AnalogMain {
	private static final Logger logger = Logger.getLogger(AnalogMain.class);
	public static float m=0,h=0;
	public static float minuteAngle=0, hourAngle=0, angleBtwnHands=0;

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		logger.info("Calling Main Method ");
			
		try{
			Scanner in = new Scanner(System.in);
			 
			System.out.println("Enter the hour");
			h =  Float.parseFloat(in.nextLine());
			
			System.out.println("Enter the minute");
			m =  Float.parseFloat(in.nextLine());
			
			getAngleBetween(h,m);
		}catch(Exception e){
			logger.error("Error while processing values from the user : "+e);
		}
	}
	
	public static void getAngleBetween(float inputHour, float inputMinute){
		logger.info("Calling getAngleBetween(float "+inputHour+", float "+inputMinute+")");
		
		if(isValidInputs(inputHour,inputMinute)){
		    if (inputHour == 12) inputHour = 0;
		    if (inputMinute == 60) inputMinute = 0;
		    
			minuteAngle=getMinuteAngle(inputMinute); 
			hourAngle=getHourAngle(inputHour,inputMinute);
			angleBtwnHands=Math.abs(hourAngle-minuteAngle);
			
			System.out.println(angleBtwnHands);
		}else{
			System.out.println("Invalid Inputs");
		}
	}
	
	public static boolean isValidInputs(float inputHour, float inputMinute){
		logger.info("Calling validateInputs(float "+inputHour+", float "+inputMinute+")");
		boolean result=true;
		
		if (inputHour 12 || inputMinute > 60){
			result=false;
			logger.error("Invalid Input ");
		}
		return  result;
	}
	
	public static float getMinuteAngle(float inputMinute){
		logger.info("Calling getMinuteAngle( float "+inputMinute+")");
		float outputMinuteAngle=0;
		
		outputMinuteAngle=(inputMinute*6);
		System.out.println("outputMinuteAngle :"+outputMinuteAngle);
		return outputMinuteAngle;
	}
	
	public static float getHourAngle(float inputHour,float inputMinute){
		logger.info("Calling getHourAngle(float "+inputHour+", float "+inputMinute+")");
		float outputHourAngle=0;
		outputHourAngle=(float)((inputHour*60+inputMinute)*0.5);
		System.out.println("outputHourAngle : "+outputHourAngle);
		return outputHourAngle;
	}
}
Add comment
  • No comments found