2015-08-24 53 views
1

一個程序,提示用戶輸入秒數,然後每秒顯示一條消息,並在時間到期時終止。到目前爲止,我已經能夠做到這一點。但是,我卡在這裏。java中的計時器實現

public static void main(String[] args) 
    { 
    Scanner r = new Scanner(System.in); 
     int sec = r.nextInt(); 
     while (sec > 0) 
     { 
      System.out.println("Seconds Remaining" + sec); 
      /**What to do here using System.currentTimeMillis()??**/ 
      sec--; 
     } 
} 
+0

我敢肯定他們沒有到目前爲止覆蓋。有沒有其他方法? @Reimeus – Katherine

+1

http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html 文檔中的示例與您的示例幾乎完全相同... – Brick

+1

您還可以執行旋轉循環並檢查開始時間和當前時間。不是我會推薦它,但如果你沒有了解線程的話。 – John

回答

3

從「我怎樣才能使所選擇的方法中這項工作(使用的currentTimeMillis),它有一定的價值學習的目的,這樣,下一次我需要做類似的東西,這是正確的方式,我不會被卡住,即使它不是這一次的最佳方式」的觀點:

long start = System.currentTimeMillis(); 
long now = System.currentTimeMillis(); 
while (now - start > 1000) // While the difference between the two times is less than a second 
{ 
    now = System.currentTimeMillis(); 
} 

你可以前夜ñ嘗試糾正錯誤(now-start-1000畢竟可能大於1,這將會浪費時間)並計算任何多餘的時間。然後,您會在循環的條件中將這個過剩量從1000中減去,這樣下一次您就可以稍微等一點時間來彌補上次的過量。此外,System.out.println()需要時間,因此您想要在System.out.println之前設置開始,以便更準確一些。

現在,我希望我已經指出了足夠的陷阱,以證明爲什麼這對任何重要的計時都是一個壞主意。更準確的最簡單的方法是使用Timer,它使用允許將打印和其他開銷從計時中分離出來的線程。然而,它只是對上述「Object.wait()」使用了一個不太有趣但更簡單的解釋,它「不提供實時保證」。

+0

謝謝...解決了這個問題..「是任何視角」;) – Katherine

3

您正在尋找的Thread.sleep()或TimeUnit.sleep我懷疑

public static void main(String[] args) throws InterruptedException { 
    Scanner in = new Scanner(System.in); 
    for(int sec = in.nextInt(); sec > 0; sec --) { 
     System.out.println("Seconds Remaining " + sec); 
     TimeUnit.SECONDS.sleep(1); 
    } 
} 
+0

是的,它的工作......唯一的事情是我還沒有讀過關於線程。不管怎麼說,多謝拉。 :) – Katherine

3

使用線程是最合適的方法。

public static void main(String[] args) throws Exception 
{ 
    Scanner r = new Scanner(System.in); 
    int sec = r.nextInt(); 
    while (sec > 0) 
    { 
     System.out.println("Seconds Remaining" + sec); 
     /**What to do here using System.currentTimeMillis()??**/ 
     Thread.sleep(1000); 
     sec--; 
    } 
} 

希望這有助於:)

+0

是的,它的工作......但我沒有讀過關於現在的線程。不管怎麼說,多謝拉。 :) – Katherine