public class Watch
{
/**
* An indication of whether or not the clock is running
*/
private boolean running; // is the watch keeping track of time
/**
* The millisecond that the clock started.
*/
private long strt; // starting millisecond count
/**
* The total number of milliseconds elapsed.
*/
private long accum; // total milliseconds
/**
* Constructs a stopwatch for timing events to the milliseconds.
*
*
* - Postcondition:
- returns a stopped clock
*
*/
public Watch()
// post: returns a stopped watch
{
running = false;
strt = 0;
accum = 0;
}
/**
* Start the watch running.
*
*
* - Precondition:
- watch is stopped
*
- Postcondition:
- starts watch, begins measuring possibly accumulated time
*
*/
public void start()
// post: watch is stopped
// pre: starts watch, begins accumulating time
{
running = true;
strt = System.currentTimeMillis();
}
/**
* Stop the watch. Time does not accumulate.
*
*
* - Precondition:
- watch is running
*
- Postcondition:
- stops watch, and accumulates time
*
*/
public void stop()
// pre: watch is running
// post: stops watch, and accumulates time
{
running = false;
accum += (System.currentTimeMillis()-strt);
}
/**
* Read the value on the stop watch.
*
*
* - Postcondition:
- returns the accumulated time on the watch
*
*
* @return A double representing the number of seconds elapsed.
*/
public double read()
// post: returns the accumulated time on the watch
{
if (running)
{
return (double)(accum+
(System.currentTimeMillis()-strt))/1000.0;
} else {
return (double)accum/1000.0;
}
}
/**
* Resets the time on the watch to zero.
*
*
* - Postcondition:
- stops running watch and clears the accumulated time.
*
*/
public void reset()
// post: stops running watch and clears the accumulated time.
{
running = false;
accum = 0;
}
/**
* Generates string representation of watch.
*
*
* - Postcondition:
- returns a string representation of the watch
*
*
* @return A string representing this watch.
*/
public String toString()
// post: returns a string representation of the watch
{
return "";
}
}