stopwatch not working

I know there’s good alternatives such as the GAGE timer, but I’ve just taught myself Java(ish) and wrote this program to get my head around some of the basics, can someone tell me why this program goes so catastrophically wrong when I run it?

 public static void main(String[] args) {
        Runnable ticker = new Timer();
        Thread t = new Thread(ticker);
        t.start();
    }

}

class Timer implements Runnable {
    long oneClock;
    long twoClock;
    int gameLength = 25;
    long diff;
    long beforeTime;
    long afterTime;
    long realTime;
    boolean loop = false;

   public void run () {
        beforeTime = System.nanoTime();
        while (gameLength > 0){
            oneClock = System.nanoTime();
            loop = true;
            
            while (loop = true) {

                try {
                Thread.sleep(10); } catch (InterruptedException ex) {ex.printStackTrace(); }
                twoClock = System.nanoTime();

                diff = twoClock - oneClock;
                if (diff >= 1) {
                gameLength -= diff;
                System.out.println (this.gameLength) ;
                loop = false;
                } //second while close
            }
       } // 1st while close

        afterTime = System.nanoTime();
        realTime = afterTime - beforeTime;
        System.out.println("The end of the clock");
        System.out.println("The clock took" + realTime + "seconds to finish");
    }
}

That’s the code, this is the output, which can tell is wrong:

-9577724
-29163946
-58738110
-98324597
-147897743
-207477652
-277060474
-356637654
-446223307
-545811873
-655405063
-774993039
-904580078
-1044161048
-1193738515
-1353326594
-1522912453

I admit before I get flamed, I am a noob, but I’d appreciate some direction. Cheers guys.

This code assigns ‘true’ to ‘loop’…


while (loop = true) {

You should replace it by:


while (loop == true) {

Or even better:


while (loop) {

 System.out.println("The clock took" + realTime + "seconds to finish");

Watch out, you’re working with nanoseconds there, not seconds.

ha lol, can’t believe I missed that thing with loop!!

I know I was working with nanoseconds, and in a previous version I multiplied the results by 1000000000 but I thought that might have been a root with the problem for some reason and edited that out.

ok so I changed the loop and multiplied each nanoTime by 1000000000 and now it gives me this result:

run:
767364121
-977696743
The end of the clock
The clock took19850560000000000seconds to finish
BUILD SUCCESSFUL (total time: 0 seconds)

So now you’re using atto-seconds.

What about dividing by 1000000000?

I discovered whythe stop watch was going crazy, I should have been dividing the nanoTime no multilying it

When I changed this, it worked, apart from it takes 24secs to finish not 25 :confused: but that’s a minor setback!

Cheers for the help :slight_smile: