输入的时间限制 [英] Time limit for an input

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

问题描述

假设我有一个代码,它要求用户给出一些输入,如下所示:

  for(condition) {
System.out.println(请给一些输入);
System.in.read();
} //让我们说这个循环重复3次,我在第二次迭代时面临一个问题

但是我想给用户60秒的时间限制,然后抛出异常(在这种情况下,我认为它的 TimeOutException )。如何做?

解决方案

  import java.util.Timer; 
import java.util.TimerTask;
import java.io. *;
public class test
{
private String str =;

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

public void getInput()throws异常
{
定时器定时器=新的Timer();
timer.schedule(task,10 * 1000);

System.out.println(在10秒内输入一个字符串);
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
str = in.readLine();

timer.cancel();
System.out.println(你输入:+ str);
}

public static void main(String [] args)
{
try
{
(new test())getInput ();
}
catch(异常e)
{
System.out.println(e);
}
System.out.println(main exit ...);
}
}


Suppose I have a code where it asks the user to give some input, something like this:

for (condition) {
System.out.println("Please give some input");
System.in.read();
} //lets say this loop repeats 3 times and i face a problem during second iteration

but I want to give the user a 60 second time limit, and then throw an exception (in this case, I think its TimeOutException). How do I do that?

解决方案

import java.util.Timer;
import java.util.TimerTask;
import java.io.*;
public class test
{
    private String str = "";

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

    public void getInput() throws Exception
    {
        Timer timer = new Timer();
        timer.schedule( task, 10*1000 );

        System.out.println( "Input a string within 10 seconds: " );
        BufferedReader in = new BufferedReader(
        new InputStreamReader( System.in ) );
        str = in.readLine();

        timer.cancel();
        System.out.println( "you have entered: "+ str ); 
    }

    public static void main( String[] args )
    {
        try
        {
            (new test()).getInput();
        }
        catch( Exception e )
        {
            System.out.println( e );
        }
        System.out.println( "main exit..." );
    }
}

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

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