3

我正在尝试重新启动 while 循环。我已经声明了布尔类型的变量 keepGoing。如果 int 变量 x 不在窗口内,则 keepGoing 更改为 false。然后reset() 方法必须保持Going=true。它可以工作,但 while 循环不起作用。

带有 reset() 和 checkWin() 的类:

private void reset() {
    b.x = 250;
    b.y = 100;
    b.keepRunning = true;
    a.keepGoing = true;
    System.out.println(a.keepGoing);
}

public void checkWin() {
    if (b.keepRunning) {
        if (b.getX() < -10) {
            a.score++;

            JOptionPane.showMessageDialog(okno, "Player " + p.getScore()
                    + " - Computer " + a.getScore(), "Oh, well...",
                    JOptionPane.INFORMATION_MESSAGE);
            b.keepRunning = false;
            a.keepGoing = false;
            System.out.println(a.keepGoing);
            reset();
        } else if (b.getX() > 599) {
            p.score++;
            JOptionPane.showMessageDialog(okno, "Player " + p.getScore()
                    + " - Computer " + a.getScore(), "Good!",
                    JOptionPane.INFORMATION_MESSAGE);
            b.keepRunning = false;
            a.keepGoing = false;
            System.out.println(a.keepGoing);
            reset();
        }
    }
}

带线程的第二类,keepGoing 和 while 循环:

Runnable intel = new Runnable() {
    public void run() {
        while (keepGoing) {
            while (getY() < board.ball.getY()) {
                System.out.println(keepGoing + " " + getY());
                try {
                    if (y == 220) {
                    } else {
                        y += 1;
                        Thread.sleep(10);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            while (getY() > board.ball.getY()) {
                System.out.println(keepGoing + " " + getY());
                try {
                    if (y == 0) {
                    } else {
                        y -= 1;
                        Thread.sleep(10);
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
};
4

2 回答 2

11

使用关键字continue进入循环的下一个迭代。例如:

while(true)
{
   // ...

   if(!condition) continue; // this will go to the beginning of the while loop.

   // ...
}
于 2012-07-11T16:47:12.993 回答
1

如果keepGoing标志是从不同的线程访问的(我认为您的示例正在显示,尚不清楚),那么您需要使用同步来确保当您keepGoing在 reset() 方法中更新标志时,它对中的线程可见你的可运行文件。您可能想查看AtomicBoolean课程。

参见 Effective Java,Item #66

于 2012-07-11T16:54:53.423 回答