gpt4 book ai didi

java - 在特定时间接收输入

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:39:41 27 4
gpt4 key购买 nike

我正在编写一个测试系统,我只想计算用户在这个问题上花费了多少秒。即我打印问题(标准 System.out.println),然后等待 5 秒,如果在这 5 秒内用户回答(通过标准输入),我想保留这个值。

如果用户在 5 秒内没有提供答案,则必须跳过此问题并继续。

问题是我正在通过 Scanner 对象读取用户答案,我想像 in.nextInt() 这样的东西是无法控制的。

我该如何解决这个问题?这是我没有该功能的代码片段,您能给我一些提示,告诉我要添加什么吗?

    public void start() {
questions.prepareQuestions(numQuestions);
Scanner in=new Scanner(System.in);
boolean playerIsRight=false,botIsRight=false;
int playerScore=0,botScore=0;
for (int i = 0; i < numQuestions; i++) {
questions.askQuestion(i);
System.out.print("Your answer(number): ");
playerIsRight=questions.checkAnswer(i,in.nextInt()-1); //in.nextInt() contains the answer
botIsRight=botAnswersCorrectly(i + 1);
if(playerIsRight){ playerScore++; System.out.println("Correct!");}
else System.out.println("Incorrect!");
if(botIsRight) botScore++;
System.out.print("\n");
}
if(botScore>playerScore) System.out.println("Machine won! Hail to the almighty transistors!");
else if(playerScore>botScore) System.out.println("Human won! Hail to the power of nature!");
else System.out.println("Tie. No one ever wins. No one finally loses.");
}

最佳答案

在这种情况下,我会使用两个线程。主线程写题,等待答案,记分。一个子线程读取标准输入并将答案发送给主线程,可能是通过 BlockingQueue .

主线程可以通过在阻塞队列上使用 poll() 方法等待五秒钟以获取答案:


BlockingQueue<Integer> answers = new SynchronousQueue();
Thread t = new ReaderThread(answers);
t.start();
for (int i = 0; i < numQuestions; ++i) {
questions.askQuestion(i);
System.out.print("Your answer (number): ");
Integer answer = answers.poll(5, TimeUnit.SECONDS);
playerIsRight = (answer != null) && questions.checkAnswer(i, answer - 1);

}
t.interrupt();

如果此调用返回null,则主线程知道子线程在那段时间没有收到任何输入,并且可以适本地更新分数并打印下一个问题。

ReaderThread 看起来像这样:

class ReaderThread extends Thread {

private final BlockingQueue<Integer> answers;

ReaderThread(BlockingQueue<Integer> answers) {
this.answers = answers;
}

@Override
public void run() {
Scanner in = new Scanner(System.in);
while (!Thread.interrupted())
answers.add(in.nextInt());
}

}

System.in上使用,Scanner会阻塞,直到用户按下Enter,所以可能会发生用户已经输入了一些当主线程超时并继续下一个问题时,文本但尚未按下 Enter。用户将不得不删除他们的未决条目并为新问题输入新答案。我不知道有什么方法可以解决这种尴尬,因为没有可靠的方法来中断 nextInt() 调用。

关于java - 在特定时间接收输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4228849/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com