This is an exercise question taken from Java Software Solutions: foundations of program design by Lewis & Loftus, 4th edition ; Question PP2.6 (here is a link)
Question is as follows: " Create a project that reads a value representing a number of seconds, then print the equivalent amount of time as a combination of hours, minutes, and seconds. (For example, 9999 seconds is equivalent to 2 hours, 46 minutes, and 39 seconds.)"
I have so far tried the following
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double totalSecs, seconds, minutes, hours;
System.out.println("Enter number of seconds: ");
totalSecs = scan.nextInt();
hours = totalSecs/3600;
minutes = (Math.abs(Math.round(hours)-hours))*60;
seconds = (Math.abs(Math.round(minutes)-minutes))*60;
System.out.print(hours + "\n" + minutes + "\n" + seconds);
}
Answer came out to, hours: 2.7775 minutes: 13.350000000000009 seconds: 21.00000000000051
What I want to do is take the decimals of, say, hours and multiply them by 60 to get minutes and repeat the process for seconds. I'm however having trouble figuring it out, hence the messy solution of (Math.abs) etc.
What would you recommend me to change/add? Thanks!
Note: This is a book for beginners, hence I've not learned many more operations than those I've already stated in the code. As such, I haven't understood the solution for the previous times this question has been asked.
As an alternative of user2004685's answer;
Here is a much simpler way of doing it:
Note: Please note that this will only show the output in 24-hour format and if number of hours is greater than 24 then it'll increment a day and will start over. For example, 30 hours will be displayed as
06:xx:xx
. Also, you'll have to pass the input in milliseconds instead of seconds.If you want to do it your way then you should probably do something like this:
Output: