The following question was taken from Absolute Java 5th ed. by Walter Savitch:
Write a program that outputs the number of hours, minutes, and seconds that corresponds to 50,391 total seconds. The output should be 13 hours, 59 minutes, and 51 seconds. Test your program with a different number of total seconds to ensure that it works for other cases.
This is the code that I have written:
public class Question7 {
private static final int MINUTES_IN_AN_HOUR = 60;
private static final int SECONDS_IN_A_MINUTE = 60;
public static void main(String[] args) {
int seconds = 50391;
System.out.println(timeConversion(seconds));
}
private static String timeConversion(int totalSeconds) {
int hours = totalSeconds / MINUTES_IN_AN_HOUR / SECONDS_IN_A_MINUTE;
int minutes = (totalSeconds - (hoursToSeconds(hours)))
/ SECONDS_IN_A_MINUTE;
int seconds = totalSeconds
- ((hoursToSeconds(hours)) + (minutesToSeconds(minutes)));
return hours + " hours " + minutes + " minutes " + seconds + " seconds";
}
private static int hoursToSeconds(int hours) {
return hours * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE;
}
private static int minutesToSeconds(int minutes) {
return minutes * SECONDS_IN_A_MINUTE;
}
}