OntologicalSin OntologicalSin - 3 months ago 11
Java Question

Java time conversions

Scanner input2 = new Scanner(System.in);
System.out.println("Time to be converted to hh:mm:ss: ");
int time = input2.nextInt();
int hr = 0, min = 0, sec = 0;
if(time >= 3600)
{
hr = time/3600;
time = time%3600;
}
if(time >= 60)
{
time = time%3600;
min = time/60;
}
if (time < 60)
{
sec += time;
}
System.out.println(hr+":"+min+":"+sec);


So, my problem is that whenever the seconds is greater than 3719, the minutes and hours stop incrementing.

Example:

3719
1:1:59

3720
1:1:0

7325
1:1:0


Ive also tried a different algorithm, using subtraction instead of modulus

Scanner input2 = new Scanner(System.in);
System.out.println("Time to be converted to hh:mm:ss: ");
int time = input2.nextInt();
int hr = 0, min = 0, sec = 0;
if(time >= 3600)
{
hr ++;
time -=3600;
}
if(time >= 60)
{
time -= 60;
min ++;
}
if (time < 60)
{
sec += time;
}
System.out.println(hr+":"+min+":"+sec);

Answer

That's because you are using 3600 in modulus for min:

if (time >= 60) {
    min = time / 60;
    time = time % 3600;
}

but you must use 60, change it to:

public static void main(String[] args) {
    Scanner input2 = new Scanner(System.in);
    System.out.println("Time to be converted to hh:mm:ss: ");
    int time = input2.nextInt();
    int hr = 0, min = 0, sec = 0;
    if (time >= 3600) {
        hr = time / 3600;
        time = time % 3600;
    }
    if (time >= 60) {
        min = time / 60;
        time = time % 60;
    }
    if (time < 60) {
        sec += time;
    }
    System.out.println(hr + ":" + min + ":" + sec);
}

and it will work as you expect.

Check it here http://ideone.com/unTQTW

Comments