2013-10-21 130 views
1

我是Java的初學者,我一直試圖解決這個計時器的事情,像3-4小時。已經嘗試了互聯網上的所有東西。Java時間暫停

事情是,程序應該給用戶輸入任何東西來開始新遊戲或等待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; 
} 

}

但出於某種原因,我不能讓它開始工作,一直在努力得到這個工作和計算器是我最後一次機會。

編輯:謝謝大家的回覆。還沒有修復,從這個令人頭疼,現在是03:31。

+2

'end.nextLine'是阻塞方法。它會等待,直到你輸入一些東西 – MadProgrammer

+0

你缺少一個括號。它放在哪裏? –

+1

如果沒有多線程,則無法完成此操作。 – bstempi

回答

1

UsingTimerTaskhttp://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()); 
     } 
    } 
} 
+0

這是行不通的。 'hasNext()'直到輸入緩衝區中有東西纔會返回。 – tbodt

+0

謝謝,我修復了代碼。 – iamreptar

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(); 
+0

'stop'已棄用,*「本質上不安全」* - 請參閱[Java Thread Primitive Deprecation](http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html)更多細節... – MadProgrammer

+0

好吧,它是固定的。謝謝你讓我知道! – john01dav

+0

這將使'inputThread'無限期地被阻塞在'end.nextLine'方法中。它可能甚至影響未來的輸入功能...... – MadProgrammer