输入的时间限制 [英] Time limit for an input
本文介绍了输入的时间限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个代码,它要求用户提供一些输入,如下所示:
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
但我想给用户 60 秒的时间限制,然后抛出异常(在这种情况下,我认为是 TimeOutException
).我该怎么做?
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屋!
查看全文