时限输入

时限输入

问题描述:

假设我有它要求用户给予一定的输入代码,像这样:时限输入

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

Duplicate:http://stackoverflow.com/questions/804951/is-it-possible-to-read-from-a-java-inputstream-with-a-timeout – cnicutar 2011-05-02 06:32:01

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..."); 
    } 
} 
+0

还有其他更简单的方法吗?因为我在我的java.util包中没有timer和timertask类 – hari 2011-05-02 06:34:53

+0

开始线程,只需在while循环中使用你的时间和间隔后使用thread.destroy(); – 2011-05-02 06:47:36

+0

我有话要问u..lets说我写了这个 - Thread t = new Thread(); t.start(); //我开始了线程 do {// my logic} while(condition); t.destroy(); //我摧毁了线程,但不知道为什么。 我的代码框架是否正确? ()时,我必须放入什么条件? 你能否清楚我所有的疑惑? – hari 2011-05-02 09:42:45

我使用乔达时间用于这种东西:

行家:

<!-- 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

欢呼

+0

还有其他更简单的方法吗?因为我没有在我的项目中使用该maven。 – hari 2011-05-02 06:34:05

+0

您可以在不使用maven的情况下使用joda时间:p – chzbrgla 2011-05-02 06:38:46

怎么这么简单的东西:

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

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

+0

这将一直等到您提供输入。 – 2017-03-28 17:07:41