0

我创建了一个简单的游戏,要求您在一定的回合数内猜测一个数字(例如 10)。然而,这使得很容易被击败。我需要帮助的是如何跟踪游戏进行了多长时间。

这是我到目前为止所想到的(减去游戏逻辑),但它似乎不起作用

Random ranNum = new Random();   
double input;   // The input
long startTime; // The time the game started
long curTime;   // The time the game ended

    double randNum = ranNum.nextInt(100);

while (curTime > 1000){
            curTime = System.currentTimeMillis();
            input = TextIO.getlnDouble();

            if (input = Math.abs(randNum)){
                System.out.println("You got the correct answer");

            }   // End if statement

            else {
                System.out.println("You did not have the correct answer");
                System.out.println("The number was" + randNum + ".");

            }   // End else statement

        } // End while statement
4

2 回答 2

0

are you not using startTime ?

long startTime = System.currentTimeMillis();

currTime = System.currentTimeMillis() - startTime

Now the currTime will have the time difference in milliseconds.

于 2013-10-06T18:32:28.000 回答
0

您必须在循环开始之前获取当前时间戳:

startTime = System.currentTimeMillis(); //get timestamp

//the condition is waaaay off, basically equals to while (true) - more on that later
while (curTime > 1000){
        input = TextIO.getlnDouble();

        if (input = Math.abs(randNum)){
            System.out.println("You got the correct answer");

        }   // End if statement

        else {
            System.out.println("You did not have the correct answer");
            System.out.println("The number was" + randNum + ".");

        }   // End else statement

    } // End while statement

curTime = System.currentTimeMillis(); //get timestamp again

System.out.println("Game took " + ((curTime-startTime)/1000) + " seconds");

System类的文档中:

公共静态长 currentTimeMillis()

以毫秒为单位返回当前时间。请注意,虽然返回值的时间单位是毫秒,但值的粒度取决于底层操作系统,并且可能更大。例如,许多操作系统以几十毫秒为单位测量时间。

有关“计算机时间”和协调世界时 (UTC) 之间可能出现的细微差异的讨论,请参阅类 Date 的描述。

回报:

当前时间与 UTC 1970 年 1 月 1 日午夜之间的差异,以毫秒为单位。

所以要获得游戏的持续时间,你必须取两个时间戳,并从前者中提取后者......

此外,while 循环条件很差......这个

while (curTime > 1000){

基本上是true......它只会在 1970 年 1 月 1 日,从 00:00:00 到 00:00:01 为假

你可能有这样的事情:

while(curTime-startTime > 10000) { //remember, value is ms!
   //...loop content
   curTime = System.currentTimeInMillis(); //update timestamp
}

但它不会让游戏在 10 秒后结束。如果您想限制游戏可以进行多长时间,那是另一种 cookie - 您必须有另一个线程才能完成...

于 2013-10-06T18:34:48.600 回答