Shlomo Zalman Heigh
Shlomo Zalman Heigh

Reputation: 3978

Java Endless While Loop

I have the following code:

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
}

The problem is that the while loop is endless and the else part only runs 8 times. What is going on here?

Upvotes: 1

Views: 227

Answers (3)

La2o
La2o

Reputation: 1

Add the generateRandom method so we can fix your problem.

Upvotes: 0

Tala
Tala

Reputation: 8938

The only possibility I see is that your generateRandom method generates numbers in range 0..7 (only 8 numbers, not 9) or 1..8 for example

Upvotes: 3

William Morrison
William Morrison

Reputation: 11006

I'm guessing its because your generateRandom function isn't returning a correct range.

Upvotes: 2

Related Questions