I want the user to solve a simple quiz. The user has 30 seconds to give an answer. While he is thinking about that I want to display a countdown from 30 seconds.
If there was no answer the quiz should terminate and display TIMEOUT. So I started with a simple Countdown class:
public class Countdown implements Runnable{
public Countdown(){}
public void run(){
try{
//so let's start counting
for(int i = 30; i > 0; i--){
Thread.sleep(1000);
System.out.println(i);
}
}catch(InterruptedException e){
System.out.println("Countdown interrupted");
}
System.out.println("TIMEOUT");
}
}
Both when user gives the right or wrong answer the quiz shoud terminate.
import java.io.*;
import java.util.*;
public class MathQuiz{
public static void main(String args[]){
//so this is our simple quiz
System.out.println("19*24-1=?");
Thread thread = new Thread(new Countdown());
thread.start();
try{
Scanner sc = new Scanner(System.in);
String text = sc.nextLine();
if(!(thread.getState()).equals("TERMINATED")){
if(text.equals("455")){
System.out.println("Right!");
}else{
System.out.println("Wrong!");
}
thread.interrupt();
}else{
sc.close();
}
}catch(Exception e){
System.out.println(e.toString());
}
}
}
When the user gives the right or wrong answer the quiz terminates but gives me a timeout message too. So this is the first problem.
Another problem is that when I wait for the timeout the scanner is still open and waiting for input.
I think there might be something wrong with fetching the thread state.
Any ideas?
do this
use another thread to get input form user and interrupt it after 30 sec
see this for example