1

我是 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。

4

2 回答 2

1

使用 TimerTaskhttp://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());
        }
    }
}
于 2013-10-21T00:59:38.913 回答
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();
于 2013-10-21T01:08:20.720 回答