首页 / JAVA / java-在特定时间接收输入
java-在特定时间接收输入
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-在特定时间接收输入,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2422字,纯文字阅读大概需要4分钟。
内容图文
![java-在特定时间接收输入](/upload/InfoBanner/zyjiaocheng/694/5b9e0bd6fe1c4322a2189b0dd560877c.jpg)
我正在编写一个测试系统,我要做的就是计算用户在此问题上花费了多少秒.即我打印问题(标准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上使用时,扫描程序将一直阻塞,直到用户按下Enter键为止,因此当主线程超时并继续下一个问题时,用户可能已经输入了一些文本但尚未按下Enter键.用户将不得不删除他们的待处理条目,并为新问题输入新答案.我不知道如何解决这种尴尬,因为没有可靠的方法来中断nextInt()调用.
内容总结
以上是互联网集市为您收集整理的java-在特定时间接收输入全部内容,希望文章能够帮你解决java-在特定时间接收输入所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。