-6

I want to create a timer, given a set amount of time the user has to answer the question within the allotted time, if he/she fails to do so, the user no longer has the option to enter the answer

I've tried timer. I need a separate thread to check in if the allotted time is up and then exit the loop.

Tamir Shklaz
  • 307
  • 2
  • 14
  • 2
    Have you tried the class....`Timer` ? – Tim B May 03 '14 at 13:53
  • I'm not voting to close this as a duplicate, but as unclear. Tamir, you said that you've tried timer, maybe you should elaborate more on your problems? Why wouldn't Timer do what you needed it to? – Erick Robertson May 03 '14 at 14:17

2 Answers2

0

By Using java.util.Timer

Timer timer = new Timer();
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
0
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class Stopwatch {
static int interval;
static Timer timer;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Input seconds => : ");
    String secs = sc.nextLine();
    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval = Integer.parseInt(secs);
    System.out.println(secs);
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            System.out.println(setInterval());

        }
    }, delay, period);
}

private static final int setInterval() {
    if (interval == 1)
        timer.cancel();
    return --interval;
}
}