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?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| 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; } } }
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| -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.