-4

I found this stopwatch java code from somewhere on the Internet, but it does not seem to be working. I was wondering how to fix this code to make it work. It's supposed to have features to start, stop and reset, and should display the time as hours:minutes:seconds.milliseconds (example: 12:35:17.26). Please help me.

public class StopWatch {

private long startTime = 0;
private long stopTime = 0;
private boolean running = false;


public void start() {
    this.startTime = System.currentTimeMillis();
    this.running = true;
}


public void stop() {
    this.stopTime = System.currentTimeMillis();
    this.running = false;
}


//elaspsed time in milliseconds
public long getElapsedTime() {
    long elapsed;
    if (running) {
         elapsed = (System.currentTimeMillis() - startTime);
    }
    else {
        elapsed = (stopTime - startTime);
    }
    return elapsed;
}


//elaspsed time in seconds
public long getElapsedTimeSecs() {
    long elapsed;
    if (running) {
        elapsed = ((System.currentTimeMillis() - startTime) / 1000);
    }
    else {
        elapsed = ((stopTime - startTime) / 1000);
    }
    return elapsed;
}




//sample usage
public static void main(String[] args) {
    StopWatch s = new StopWatch();
    s.start();
    //code you want to time goes here
    s.stop();
    System.out.println("elapsed time in milliseconds: " + s.getElapsedTime());
}
}
rjdkolb
  • 10,377
  • 11
  • 69
  • 89
Fawzan Izy
  • 1,780
  • 3
  • 14
  • 16

3 Answers3

3

This example shows how to start and stop a javax.swing.Timer. Several approaches to formatting are shown here. Reset is left as an exercise.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

By the level of your assignment, sounds like your professor wants you to use nested loops, which are not being used in the example you took from the web.

I won't give you the full answer, but it's fairly simple: outer-most loop is for hours, the one inside hours is for minutes, the one inside minutes for seconds, and the one inside seconds for milliseconds. The inner-most loop (milliseconds), is the one that prints the current time.

Something like this:

// 24 hours in a day
for(int hours = 0; hours < 24; hours++)
{
    // 60 mins in an hours
    for(int minutes = 0; minutes < 60; minutes++)
    {
       // 60 secs in a min
       for(int seconds = 0; seconds < 60; seconds++)
       {
           // 1000 ms in a sec.
           for(int ms = 0; ms < 1000; ms++)
           {
               System.out.println(hours + ":" + minutes + ":" + seconds + "." + ms);
           }
       }
    }
}

Now make it pretty and add a 1-millisecond delay in the inner-most loop and you are done! :)

Diego
  • 18,035
  • 5
  • 62
  • 66
0

If you want to make a stopwatch you must make a Thread. The Java API states all of the functions of a thread. This is necessary, because otherwise you won't be able to pause the timer. This is because the system spends the full runtime on the counting.

Also, the script you provided is used for determining the amount of time a certain calculation took, it's not ment for timing itself.

I suggest you make 2 classes, 1 for the timer and 1 for the GUI. make the GUI with a label, a start-, stop- and reset-button.

Next, make sure the timer-class EXTENDS THREAD (or implements Runnable) and make it a thread. Next implement the functions to either stop the thread or start the thread (your start/stop buttons). The Reset should be easy after that (just set the timer back to 0).

The StopWatch-class could look like this:

public class Stopwatch extends Thread 
{
    private long startTime;
    private boolean started;

    public void startThread()
    {
        this.startTime = System.currentTimeMillis();
        this.started = true;
        this.start();
    }

    public void run()
    {
        while (started)
        {
            // empty code since currentTimeMillis increases by itself
        }
    }


    public int[] getTime()
    {
        long milliTime = System.currentTimeMillis() - this.startTime;
        int[] out = new int[]{0, 0, 0, 0};
        out[0] = (int)(milliTime / 3600000      );
        out[1] = (int)(milliTime / 60000        ) % 60;
        out[2] = (int)(milliTime / 1000         ) % 60;
        out[3] = (int)(milliTime)                 % 1000;

        return out;
    }

    public void stopThread()
    {
        this.started = false;
    }
}

In the GUI-class you would make start call the 'startThread', stop call the StopWatch.stop(); (which is a Thread-function) and make reset call the reset().

This should get you started with a basic stopwatch. A (bad) example for its useage:

public static void main(String[] args) throws InterruptedException
    {
        Stopwatch s = new Stopwatch();

        s.startThread();

        while (true)
        {
            int[] curTime = s.getTime();
            System.out.println(curTime[0] + " : " + curTime[1] + " : " + curTime[2] + " : " + curTime[3]);
        }

    }

It would actually be more sensible to do the calculations on the currentTimeMillis outside of the threadclass.

bas
  • 1,678
  • 12
  • 23
  • i tried using `public static void main(String[] args) { StopWatch s = new StopWatch(); s.startThread(); System.out.println(s.getTime()); }` this code. but it resulted 0 on the console. why is it? – Fawzan Izy Mar 02 '12 at 08:15
  • If you query the getTime directly after starting the thread, it may not have changed its values yet. – bas Jan 22 '13 at 20:28