[英]Java System.currentTimeMillis() problem
所以在我的java類中,我們有一個家庭作業,使用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。
首先,以毫秒為單位的系統時間應表示為長,而不是雙倍。
其次,你需要創建一個變量,它保存自上次單擊(timerS)以來的時間實例變量,它當前是本地方法,因此每次都重置。
簡而言之,改變:
double timerS=0;
從局部變量到實例變量和long:
public class ElapsedTimeClient extends WindowController {
long timerS;
timerS變量在onMouseClick方法內聲明,因此只存在於此方法中。 第一次單擊鼠標后,該變量消失,無法用於比較時間。
相反,您應該使用類變量來存儲此信息。
你的問題是:
timerS
應該是類的一個字段 (不是局部變量),否則它的值將不會在對方法的調用之間保持 timerS
應為long
類型 - 從系統時間返回的類型 也:
count
應該是int
類型 除了提到的其他答案之外, System.nanoTime
是此類測量的首選方法。 該方法測量的是納秒數,而不是測量“時鍾時間”的差異。 您經常會發現currentTimeMilils
的分辨率不會超過16 ms左右,而nanoTime
可以解析更小的間隔。
timerS不需要double類型。 currentTimeMillis()返回long。
為什么會這樣? 如果你使用這樣的雙重類型:
(double - long) / 1000,
這被解釋為:
double / double = double
所以在結果中你有“精確”值(例如1.316639174817E9)而不是長值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.