我是Java的初学者,我一直在努力解决这个计时器问题3-4个小时。在互联网上尝试了几乎所有的东西。
问题是该程序应该为用户提供键入任何内容以启动新游戏或等待10秒的选项,并且他将被重定向到菜单。
这就是我的代码的样子:
long startTime = System.currentTimeMillis();
long maxDurationInMilliseconds = 10000;
while (System.currentTimeMillis() < startTime + maxDurationInMilliseconds) {
Scanner end = new Scanner (System.in);
System.out.println("Enter anything if you want to start a new game or wait 10 seconds and you will be redirected to the Menu");
String value;
value = end.nextLine();
if (value != null) {
playGame();
}
else if (System.currentTimeMillis() > startTime + maxDurationInMilliseconds) {
// stop running early
showMainMenu();
break;
}
}
但由于某种原因,我无法让它工作,一直在努力让这个工作,stackoverflow是我的最后一次机会。
编辑:谢谢大家的回复。尚未修复,从此开始头痛,这是03:31 AM。答案 0 :(得分:1)
Using TimerTask
(http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html):
public class MyClass {
private static final int TEN_SECONDS = 10000;
private String userInput = "";
TimerTask timerTask = new TimerTask(){
public void run() {
if(userInput.equals(""))
showMainMenu();
}
};
public void getInput() throws Exception {
Timer timer = new Timer();
timer.schedule(timerTask, TEN_SECONDS);
System.out.println("Press any key or wait 10 seconds to be redirected to the Menu.");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
userInput = in.readLine();
timer.cancel();
if (!userInput.equals(""))
playGame();
}
public static void main(String[] args) {
try {
(new MyClass()).getInput();
} catch( Exception e ){
System.out.println(e.getMessage());
}
}
}
答案 1 :(得分:0)
//make this booean part of the class and not function
Boolean isStopped = false;
System.out.println("Enter anything to start new game.");
Scanner end = new Scanner (System.in);
final Thread startThread = new Thread(new Runnable(){
public void run(){
try{
Thread.sleep(10000);
if(!isStopped)
showMenu();
}catch(Exception e){
e.printStackTrace();
}
}
});
final Thread inputThread = new Thread(new Runnable(){
public void run(){
end.nextLine();
isStopped = true;
startGame();
}
});
inputThread.start();
startThread.start();