2016-09-26 42 views
0

我目前正在进行问答游戏,我希望能够在游戏开始时启动计时器,然后在游戏结束时结束计时器。然后我想打印出玩家完成游戏需要多长时间。有没有简单的方法来做到这一点?显示用户在Java中执行某些操作需要多长时间

编辑:谢谢xenteros!我所要做的只是从“long difference = stopTime - startTime;”中删除“long” ,在该行代码之前创建一个像这样的“long difference”的变量,并初始化“startTime”变量。

回答

1

如果您的用户的行为代码应该是单一方法:

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"); 

} 
+0

当我把它放在第一行代码 – KobiF

+0

中的“startTime无法解析为变量”时,现在它只是表示重复的局部变量。 @xenteros – KobiF

+0

@KobiF你需要解释你是如何使用这个答案的代码。如果变量不能被解析,那么你在使用它之前没有声明它,或者你试图在它的作用域之外使用它(例如当你用一种方法声明它,但试图在另一个中声明它时)。 – Pshemo

0

在main方法的开头:

final long startTime = System.nanoTime(); 

,然后在你的方法结束:

final long duration = System.nanoTime() - startTime; 

,并打印

System.out.println(duration); 
+0

当我把那些它说:“开始时间不能被解析为一个变量”的第二行代码。 – KobiF

+0

@KobiF检查变量的范围 – deviantxdes

+0

使用nanoTime不稳定。 @KobiF我给你的工作解决方案。 – xenteros

相关问题