假设我有一个代码,它要求用户提供一些输入,如下所示:
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
)。我该怎么做?
答案 0 :(得分:3)
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..." );
}
}
答案 1 :(得分:2)
我使用joda-time来做这种事情:
行家:
<!-- Joda Time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>1.6.2</version>
</dependency>
提示输入时,设置LocalDateTime变量:
LocalDateTime timeOut = new LocalDateTime().plusSeconds(15);
循环直到用户输入或达到超时:
if (timeOut.isBefore(new LocalDateTime())) {
//throw your exception if this case happens
}
在进行投票之前:这只是一个快速:p
欢呼声
答案 2 :(得分:-2)
如此简单的事情:
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
long limit = 5000L;
long startTime = System.currentTimeMillis();
Long l = reader.nextLong();
if ((startTime + limit) < System.currentTimeMillis())
System.out.println("Sorry, your answer is too late");
else
System.out.println("Your answer is on time");
这不会引发异常,只会告诉用户他的回答太迟了。 (与提到这篇文章的另一个问题有关)。