我正在构建一个程序来询问乘法,我想设置一个计时器来强制这个人在给定的时间内给出答案:
- 如果此人在计时器结束前回答:进行下一个乘法
- 如果计时器结束,停止等待用户输入:进行下一个乘法
目前,案例1可以完成,但2不是,我正在考虑一种return;从方法中获取方法的方法,比如线程之类的,但我不知道如何
所以我面临一个问题,如果 aScanner是打开的,等待输入,如何停止它?我试过把它放在一个线程和interrupt()它或boolean用作标志,但它并没有停止Scanner
class Multiplication extends Calcul {
Multiplication() { super((nb1, nb2) -> nb1 * nb2); }
@Override
public String toString() { return getNb1() + "*" + getNb2(); }
}
abstract class Calcul {
private int nb1, nb2;
private boolean valid;
private boolean inTime = true;
private boolean answered = false;
private BiFunction<Integer, Integer, Integer> function;
Calcul(BiFunction<Integer, Integer, Integer> f) {
this.nb1 = new Random().nextInt(11);
this.nb2 = new Random().nextInt(11);
this.function = f;
}
void start() {
Scanner sc = new Scanner(System.in);
System.out.println("What much is " + this + " ?");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (!answered) {
inTime = false;
}
}
}, 5 * 1000);
int answer = Integer.parseInt(sc.nextLine());
if (inTime) {
checkAnswer(answer);
timer.cancel();
}
}
private void checkAnswer(int answer) {
System.out.println("You said " + answer);
valid = (function.apply(nb1, nb2) == answer) && inTime;
answered = true;
}
int getNb1() { return nb1; }
int getNb2() { return nb2; }
boolean isValid() { return valid; }
public static void main(String[] args) {
List<Calcul> l = Arrays.asList(new Multiplication(), new Multiplication(), new Multiplication());
l.forEach(Calcul::start);
}
}