Hi, I just started working with Java for a class and Im a little confused. My code is supposed to convert seconds to hours, minutes and the remainder of seconds. for whatever reason my answer is 8 seconds off of what it should be. The example I was given is 20000 seconds has an output of 5 hours, 33 minutes and 20 seconds. My answer is coming out as 5 hours, 33 minutes and 20 seconds. I can't find my mistake--the hours and minutes work fine. maybe someone else can find my error? My code is as follows. Thanks!

//****************************************************
// Lab:ConvertFromSeconds.java Author: Lindsey S
//****************************************************

import java.util.Scanner;

public class ConvertFromSeconds
{
//-------------------------------------------------------------------
//converts Number of seconds to Number of hours, minutes and seconds
//-------------------------------------------------------------------


public static void main (String[] args) 
{
Scanner scan = new Scanner (System.in);

System.out.print ("Time in Seconds: ");
    int seconds;

    seconds = scan.nextInt();

int hours = seconds/3600;
int restHour = seconds%3600;
int minutes = restHour/60;
int sec = restHour%60; 
int RemainderOfSeconds = seconds % (hours+minutes) ;

System.out.print(+hours + " hours, ");
System.out.print( + minutes + " minutes and ");
System.out.print( + RemainderOfSeconds + " seconds");

}
}

Recommended Answers

All 5 Replies

when I run your code here, I get:

Time in Seconds: 20000
5 hours, 33 minutes and 12 seconds

have you saved and recompiled after you changed your code and ran it again?

Your output would be correct if you printed sec as the number of seconds instead of RemainderOfSeconds. RemainderOfSeconds isn't meaningful anyway because you throw away the difference between hours and minutes. Using your example numbers, what is 20000 % (5 + 33) supposed to represent?

It's supposed to represent 20000 seconds = 5 hours, 33 minutes and 20 seconds but it comes out as 12 seconds. Just realized I said i was getting the correct answer in my first post. Sorry!

It's supposed to represent 20000 seconds = 5 hours, 33 minutes and 20 seconds but it comes out as 12 seconds

Yes, 20000 % (5 + 33) is indeed 12. Your sec variable has the correct value of 20, but you don't print it.

Thank you! that was so easy I feel stupid...but thanks so much I really appreciate it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.