1

我有以下代码:

boolean[] usedInts = {false, false, false, false, false, false, false, false, false};
for(int i = 0; i <= 8; i++) {
    JLabel square = squares[i];

    // Declare coordinate
    Coordinate coordinate = null;

    boolean keepGoing = true;
    while (keepGoing) {
        // Get random number
        int rand = generateRandom();

        if (usedInts[rand]) {
            keepGoing = true;
        } else {
            // Save that we used it
            usedInts[rand] = true;
            keepGoing = false;
        }
        // Initialize coordinate
        coordinate = coordinates[rand];
    }

    // Set square coordinates
    square.setLocation(coordinate.getX(), coordinate.getY());
    // Set used to true
}

问题是while循环是无限的,else部分只运行了 8 次。这里发生了什么?

4

3 回答 3

3

我看到的唯一可能性是您的generateRandom方法生成范围为 0..7 的数字(只有 8 个数字,而不是 9)或 1..8 例如

于 2013-07-01T19:37:57.233 回答
2

我猜是因为你的 generateRandom 函数没有返回正确的范围。

于 2013-07-01T19:37:56.317 回答
0

添加generateRandom方法,以便我们解决您的问题。

于 2013-07-01T22:21:48.853 回答