In this program converting one time unit value to hour, minute and second. Generally such type of questions asked in interview to check programming logic.
See Also: Java Program : How to convert units?
import java.util.Scanner; public class TimeConversion { static int SECOND = 60*60; static int MINUTE = 60; static int HOUR = 1; public static void main(String[] args) { System.out.println("Please enter :\nh for hour\nm for minute \ns for second"); Scanner in = new Scanner(System.in); System.out.println("Convert from:"); String fromUnit = in.nextLine(); System.out.println("Value:"); int val = in.nextInt(); String convertedTime = convertTime(fromUnit,val); System.out.println("Converted Time :"+convertedTime); } private static String convertTime(String unit, int value) { int h=0,m=0,s=0,seconds=0; //Convert to seconds switch(unit) { case "h": seconds=value*SECOND; break; case "m": seconds=value*MINUTE; break; case "s": seconds=value; break; } h=seconds/SECOND; value=seconds%SECOND; m=value/MINUTE; value=value%MINUTE; s=value/SECOND; return h+" Hour "+m+" Minute "+s+" Second"; } }
Output
Please enter :
h for hour
m for minute
s for second
Convert from:
m
Value:
60
Converted Time :1 Hour 0 Minute 0 Second
You must log in to post a comment.