1

Here is my loop class:

public class Timer {

private Timer timer;
private static boolean isRunning = true;

public static void gameLoop()
{
    while(isRunning) //the loop
    {
        try {
            Main.cash--;
            Thread.sleep(2000);
        } catch (InterruptedException e) {              
            // e.printStackTrace();
        } 
    }
}
}

When I run the applet, I get a white screen, and I cannot close the applet, I have to use the terminate button in eclipse.

Dave
  • 11
  • 2
  • Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling `Thread.sleep(n)` implement a Swing `Timer` for repeating tasks or a `SwingWorker` for long running tasks. See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details. But for better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson May 03 '13 at 05:39

3 Answers3

4
while(isRunning=true) //the loop

...sets isRunning to true, then returns true (whatever the previous value of isRunning was), and thus always executes the if statement. A single = is an assignment, which in this case is almost certainly not what you want to do.

You want to use == instead:

while(isRunning==true) //the loop

Or alternatively, more concisely (and also preferably!) simply:

while(isRunning) //the loop

I assume that isRunning will be set to false elsewhere in your code, because there's nothing that sets it to false here.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • 1
    @HovercraftFullOfEels I've added that now, but wanted to demonstrate the difference between single and double equals, since that was clearly the primary conceptual issue here. – Michael Berry May 02 '13 at 23:47
  • I have it now set to while(isRunning), but I still get a white screen, anything else I should do? (Edited the question to include the edit) – Dave May 03 '13 at 00:29
4

In your while loop, you attempt to compare boolean values with =, but that's the assignment operator. It's always true and this results in an infinite loop.

Use == to compare boolean values.

Or better, just use while (isRunning).

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

There are two issues.

First your using the assignment operator instead of the comparison operator in the while loop.

 while(isRunning=true)

should be:

 while(isRunning==true)

Second isRunning is never set to false.

These two issues cause an infinite loop.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189