1

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?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Shlomo Zalman Heigh
  • 3,968
  • 8
  • 41
  • 71

3 Answers3

3

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

Tala
  • 8,888
  • 5
  • 34
  • 38
2

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

William Morrison
  • 10,953
  • 2
  • 31
  • 48
0

Add the generateRandom method so we can fix your problem.

La2o
  • 1
  • 1