带方法的StopWatch类

时间:2014-12-11 16:38:42

标签: java math for-loop stopwatch

好吧,所以我仍然对方法有点新意,请原谅我,如果这看起来很糟糕的话。我有一个家庭作业问题,必须是一个带有两个私有数据字段startTime和endTime的秒表类。我需要一个名为start()的方法,将startTime重置为当前时间,然后使用stop()将endTime重置为当前时间。我还需要一个getElapsed时间方法并返回该值。 这是我到目前为止所得到的:

public class stopWatch {
    private double startTime;
    private double endTime;

public static void main(String[]args) {

}

public stopWatch(double startTime) {
    startTime = System.currentTimeMillis();
}

public void start() {
    startTime = System.currentTimeMillis();

} 

public void stop() {
    endTime = System.currentTimeMillis();
}

public static void getElapsedTime(double startTime, double endTime){
    stop() - start()

}
}   

有人能请我向正确的方向迈出一步吗?我知道我需要从停止的时间中减去开始时间并返回当过去时,我只是不确定如何正确设置它。

2 个答案:

答案 0 :(得分:1)

夫妻分。

  • startTime和endTime应为longs
  • 构造函数可能不应该参与。
  • start应该将endTime设置为-1
  • getElapsedTime应该是一个实例方法,而不是参数,返回long并返回endTime - startTime
  • 看到它有效,在你的主要部分,创建一个秒表,启动计时器,调用Thread.sleep(某个时间),调用stop,打印出getElapsed。

答案 1 :(得分:0)

我必须创造完全相同的东西。我想要一个简单的Java秒表,它将开始在我的桌面上运行。这是秒表类的代码。我添加了一些格式,因此它不会返回显示自启动秒表后多少毫秒的长数字。我认为你宁愿得到一些对人类更有意义的东西,比如秒,分钟和小时,而不是几毫秒。

import java.text.DecimalFormat;

public class Stopwatch
{
    // variables
    private long startTime;
    DecimalFormat twoDigits = new DecimalFormat("00");     // These help me return strings in the correct format
    DecimalFormat threeDigits = new DecimalFormat("000");  // These help me return strings in the correct format

    // Constructor
    Stopwatch()
    {
    }

    void start()
    {
        startTime = System.currentTimeMillis();
    }

    public long getStartTime()
    {
        return startTime;
    }

    public long getElapsedTime()
    {
        return System.currentTimeMillis() - startTime;
    }

    public String getElapsedTimeString()
    {
        return (String.valueOf(twoDigits.format(getHours())) + ":" + String.valueOf(twoDigits.format(getMinutes())) + ":" + String.valueOf(twoDigits.format(getSeconds())) + "." + String.valueOf(threeDigits.format(getMilliSeconds())));
    }

    public short getMilliSeconds()
    {
        return (short)((System.currentTimeMillis() - startTime) % 1000);
    }

    public byte getSeconds()
    {
        return (byte)(((System.currentTimeMillis() - startTime) / 1000) % 60);
    }

    public byte getMinutes()
    {
        return (byte)(((System.currentTimeMillis() - startTime) / 60000) % 60);
    }
    public long getHours()
    {
        return (System.currentTimeMillis() - startTime) / 3600000;
    }
}
相关问题