我目前正在進行問答遊戲,我希望能夠在遊戲開始時啓動計時器,然後在遊戲結束時結束計時器。然後我想打印出玩家完成遊戲需要多長時間。有沒有簡單的方法來做到這一點?顯示用戶在Java中執行某些操作需要多長時間
編輯:謝謝xenteros!我所要做的只是從「long difference = stopTime - startTime;」中刪除「long」 ,在該行代碼之前創建一個像這樣的「long difference」的變量,並初始化「startTime」變量。
我目前正在進行問答遊戲,我希望能夠在遊戲開始時啓動計時器,然後在遊戲結束時結束計時器。然後我想打印出玩家完成遊戲需要多長時間。有沒有簡單的方法來做到這一點?顯示用戶在Java中執行某些操作需要多長時間
編輯:謝謝xenteros!我所要做的只是從「long difference = stopTime - startTime;」中刪除「long」 ,在該行代碼之前創建一個像這樣的「long difference」的變量,並初始化「startTime」變量。
如果您的用戶的行爲代碼應該是單一方法:
long startTime = System.currentTimeMillis();
//the method
long stopTime = System.currentTimeMillis();
long difference = stopTime - startTime;
System.out.println("The task took: " + difference + " milliseconds");
System.out.println("The task took: " + difference/1000 + " seconds");
以上是在Java中執行此操作的正確方法。
爲您提供舒適:
public static void main() {
long startTime, stopTime;
//some code
startTime = System.currentTimeMillis(); //right before user's move
//user's move
stopTime = System.currentTimeMillis();
long difference = stopTime - startTime;
System.out.println("The task took: " + difference + " milliseconds");
System.out.println("The task took: " + difference/1000 + " seconds");
}
在main方法的開頭:
final long startTime = System.nanoTime();
,然後在你的方法結束:
final long duration = System.nanoTime() - startTime;
,並打印
System.out.println(duration);
當我把那些它說:「開始時間不能被解析爲一個變量」的第二行代碼。 – KobiF
@KobiF檢查變量的範圍 – deviantxdes
使用nanoTime不穩定。 @KobiF我給你的工作解決方案。 – xenteros
當我把它放在第一行代碼 – KobiF
中的「startTime無法解析爲變量」時,現在它只是表示重複的局部變量。 @xenteros – KobiF
@KobiF你需要解釋你是如何使用這個答案的代碼。如果變量不能被解析,那麼你在使用它之前沒有聲明它,或者你試圖在它的作用域之外使用它(例如當你用一種方法聲明它,但試圖在另一箇中聲明它時)。 – Pshemo