Ajmal
Ajmal

Reputation: 544

How to use timer class

I'm a novice in Java programming and I wanted to implement the timer class in my program. I'm making a mini time-based testing system which outputs a question then time remaining and then the answer choices Example:

  1. Which operator returns the remainder of integer division? (4 minutes left...)

A. % B./ C. * D. None of the above

  1. The escape sequence that represents the new line character is: (1 minutes left...)

A. \r B. \t C. \n D. \

I don't know how to get that time remaining part. It's supposed to run in background and change right when the next question comes up

Upvotes: 0

Views: 64

Answers (1)

Mshnik
Mshnik

Reputation: 7042

You can accomplish what you're trying to do without using timer, which will probably be easier, as you're new.

There's a function called System.currentTimeMillis() that returns the current system time in milliseconds. From that, you can:

  1. Store the time when you start
  2. Do some other stuff
  3. Check the time when you stop, and calculate the time remaining

As such:

public static void main(String[] args) {
    long startTime = System.currentTimeMillis();

    // Do other stuff...

    long stopTime = System.currentTimeMillis();
    int elapsedSeconds = (int)((stopTime - startTime) / 1000);
    System.out.println(elapsedSeconds + " seconds elapsed");
}

Upvotes: 1

Related Questions