猿问

输入时间限制

假设我有一个代码,要求用户提供一些输入,例如:


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)。我怎么做?


智慧大石
浏览 366回答 3
3回答

慕尼黑8549860

我将joda-time用于此类工作:专家&nbsp; <!--&nbsp; Joda Time -->&nbsp; &nbsp; <dependency>&nbsp; &nbsp; &nbsp; &nbsp; <groupId>joda-time</groupId>&nbsp; &nbsp; &nbsp; &nbsp; <artifactId>joda-time</artifactId>&nbsp; &nbsp; &nbsp; &nbsp; <version>1.6.2</version>&nbsp; &nbsp; </dependency>提示输入时,设置LocalDateTime变量:&nbsp;LocalDateTime timeOut = new LocalDateTime().plusSeconds(15);循环直到用户输入或达到超时:&nbsp;if (timeOut.isBefore(new LocalDateTime())) {&nbsp;//throw your exception if this case happens&nbsp;}在投下反对票之前:这只是一个速记:p干杯
随时随地看视频慕课网APP

相关分类

Java
我要回答