Search code examples
javatimercountdown

Timer in Java - few problems with mins/hours decrement


I am developing a Java countdown timer. I am totally new to Java though have done some C++ before so it's not all totally new. I am having problems with this - can anyone easily see what I have done wrong in the logic?

What is happening:

On run, if you enter in for example 23 in hours leave mins blank and put in 5 secs - the 5 secs should count to 0 - the mins should go to 59 and the hours to 22. However once the 5 secs elapses all digits go to zero.

If on the input box I enter though 23 hours 1 in minutes and 5 in secs - when the 5 has elapsed it changes to 22 hours 59 mins 59 secs so I know its nearly there (just hoping I may have missed something silly.

Finally the last problem with the logic - if I for example enter 30 mins 5 secs when the 5 have elapsed the mins go to 29 the secs go to 59 and continue counting down but the hours go to -1. Code below - sorry for long post but wanted to paint the scenarios - Thanks - Colly

Integer sec = new Integer (seconds.getText ());
Integer min = new Integer (minutes.getText ());
Integer hr = new Integer (hours.getText ());
int temp1 = sec.intValue ();
int temp2 = min.intValue ();
int temp3 = hr.intValue();

temp1--;
if (temp1 == -1 )
{
    temp1 = 59;
    temp2--;
    if (temp2 == 0 && temp3 != 0)
    {
        temp2 = 59;
    }
    temp3--;
}
hr = new Integer (temp3);
sec = new Integer (temp1);
min = new Integer (temp2);
hours.setText (hr.toString ());
minutes.setText (min.toString ());
seconds.setText (sec.toString ());
if (seconds.getText ().length () == 1)
    seconds.setText ("0" + seconds.getText ());

Solution

  • Please don't do time counting manually, it is painful to write and painful to read. I don't even mention how it feels to debug it.

    The Calendar class may be interesting:

    Calendar c = Calendar.getInstance();
    c.clear(); // To reset all fields
    c.set(Calendar.HOUR_OF_DAY, 23);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 5);
    
    c.add(Calendar.SECOND, -1);
    

    And you don't have to worry about counting.