0

I am a beginner to Java and am working on a school project which is a quiz. I would like to insert a timer into my code so that the question is only answerable for 2 seconds and then the answer counts as wrong and we move on to the next question. Any help would be appreciated :) thanks in advance. what i need is to stop the question from being answerable after 2 seconds, how?

here is the code

acr = "ASCII"; //this is where i store the acronym for it to be outputted
System.out.println(acr); //this is where i output the acronym
String ans = Keyboard.readString(); //class that reads the keyboard and stores the output in string variable ans
if (ans.equalsIgnoreCase("American Standard Code For Information Exchange")) //tests if answer is correct
{
    System.out.println("Correct answer");//if the answer is correct it outputs correct
    right++;// this is irrelevant
} else {
    System.out.println("Wrong Answer - American Standard Code For Information Exchange"); //if the answer is wrong it outputs wrong answer and gives you the correct meaning
    wrong++; //this is also irrelevant
}

all i need is to find a way to make a time limit for the question. Thanks

1 Answers1

0

Check the time before and after receiving the answer to the question.

System.out.println(acr);
long start = System.nanoTime();
String ans = Keyboard.readString();
long stop = System.nanoTime();
double seconds = (stop - start) / 1_000_000_000.0;
if (seconds > 2.0) {
    System.out.println("Sorry, too slow.");
} else if (ans.equals(expected)) {
    System.out.println("Correct!");
} else {
    System.out.println("Wrong. Better luck next time.");
}
David Conrad
  • 15,432
  • 2
  • 42
  • 54