input的时间限制

假设我有一个代码,要求用户input一些东西,例如:

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秒的时间限制,然后抛出一个exception(在这种情况下,我认为它的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 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..." ); } } 

我使用这种东西的时间:

行家:

  <!-- Joda Time --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>1.6.2</version> </dependency> 

当提示input时,设置一个LocalDateTimevariables:

  LocalDateTime timeOut = new LocalDateTime().plusSeconds(15); 

并循环,直到用户input或达到超时:

  if (timeOut.isBefore(new LocalDateTime())) { //throw your exception if this case happens } 

在得票之前:这只是一个快速:页

干杯

如此简单的事情呢?

  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"); 

这不会抛出exception,只是通知用户他的回答太晚了。 (涉及到这个职位的另一个问题)。