设置用户输入(扫描仪)Java的时间限制 [英] Set Time Limit on User Input (Scanner) Java

查看:161
本文介绍了设置用户输入(扫描仪)Java的时间限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试使用Scanner类读取用户输入.有没有一种简单的方法可以使它在10秒钟后移至下一个代码块?谢谢

So I'm trying to read user input using the Scanner class. Is there a simple way to make it so that after 10 seconds it moves onto the next block of code? Thanks

推荐答案

您可以使用Timer和TimerTask. TimerTask将允许您在一定时间后运行任务,在这种情况下,您可以使用此任务停止等待用户.

You can use Timer and TimerTask. TimerTask will allow you to run a task after a certain amount of time, in this case you can use this task to stop waiting for the user.

import java.util.Timer;
import java.util.TimerTask;

...

TimerTask task = new TimerTask()
{
    public void run()
    {
        if( str.equals("") )
        {
            System.out.println( "you input nothing. exit..." );
            System.exit( 0 );
        }
    }    
};

...

Timer timer = new Timer();

timer.schedule( task, 10*1000 );

Scanner sc = new Scanner(System.in);
String in = sc.readLine();

timer.cancel();

因此,如果用户在10秒钟内未响应,则计时器将退出读取输入.我从最初的这篇帖子中偷了/改编了这个回复: 输入的时间限制

So if the user doesn't respond within 10 seconds here, the timer will quit reading input. I stole/adapted this response from this initial post: Time limit for an input

这篇关于设置用户输入(扫描仪)Java的时间限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆