user2125727
user2125727

Reputation: 175

timer in java using threads

I am developing an exam software in core java where I am conducting various tests for students.I am stuck at a piece of code where timer with countdown is set. My problem is when I display minutes its working fine but when I try to display seconds with the minutes in mm:ss format its not working.

Code is:

// for below int ti=20,si=60;
// test is for 20 minutes
public void run() {
    while (true) {
        try {
            Thread.currentThread().sleep(60000);

            for (int i = 0; i <= 60; i++) {
                etime.setText("Remaining Time:-" + ti + ":" + si);
                System.out.println("Remaining Time:-" + ti + ":" + si);
                Thread.currentThread().sleep(1000);
                si--;
            }
            ti--;
            if (ti == 0) {
                close();
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(Exam.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

Upvotes: 1

Views: 651

Answers (1)

NPE
NPE

Reputation: 500167

Once si has counted down to 0, you need to reset it to 59.

Also, the i variable is completely unnecessary, and there is an off-by-one error in your loop.

Upvotes: 1

Related Questions