gpt4 book ai didi

Java System.currentTimeMillis() 问题

转载 作者:行者123 更新时间:2023-12-02 10:52:03 24 4
gpt4 key购买 nike

因此,在我的 java 类(class)中,我们有一个作业,要求使用 System.currentTimeMillis 来显示单击之间的时间量。我已经尝试过了,但它不起作用。这是我的代码。

 1 /* Matthew Caldwell
2 * September 21, 2011
3 * Homework #4: Problem 5.8.1 pg. 149
4 * Program that displays the amount of time that passed
5 * between two mouse clicks. Nothing is displayed
6 * on the first click, then each successive click will
7 * display how much time passed between that click and
8 * the previous one.
9 */
10
11 import objectdraw.*;
12 import java.awt.*;
13
14 public class ElapsedTimeClient extends WindowController {
15
16 public static void main(String[]args) {
17 new ElapsedTimeClient().startController(800,500);
18 }
19
20 private Text title,result;
21 private double count = 0;
22
23 public void begin() {
24
25 // Set up the title and result
26 title = new Text("CLICK COUNTER",
27 canvas.getWidth() / 2,
28 20, canvas);29 title.move(-title.getWidth() / 2, 0);
30 result = new Text("", canvas.getWidth() / 2, 40, canvas);
31
32 }
33
34 public void onMouseClick(Location p) {
35
36 double timerS=0;
37
38 if(count == 0) {
39 timerS = System.currentTimeMillis();
40 } else {
41 result.setText("The time between clicks was " +
42 (System.currentTimeMillis() - timerS)/1000 +
43 " seconds.");
44 timerS = System.currentTimeMillis();
45 }
46
47 count++;
48
49 }
50
51 }

我真的不想有人完全告诉我该怎么做,但我只需要一点指导。我做了什么才导致这个错误?代码全部编译并运行得很好,但是当我单击而不是给我单击之间耗时时,它给了我一个永远不会改变的大长数字。它几乎每次都告诉我 1.316639174817E9。

最佳答案

首先,以毫秒为单位的系统时间应该表示为长整型,而不是 double 型。

其次,您需要将保存自上次单击以来的时间(timerS)的变量设置为实例变量,它当前是本地方法,因此每次都会重置。

简而言之,改变:

double timerS=0;

从局部变量,到实例变量,以及 long:

public class ElapsedTimeClient extends WindowController { 
long timerS;

关于Java System.currentTimeMillis() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7506666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com