Search code examples
javaarraysfor-looppoker

Enhanced For Loop not changing all elements of my array


I am currently working on a program that will roll 5 dice and store a random number for each dice in an array. My problem is my method is only changing the first element and leaving the rest of the elements as 0's. (Only rolling the first dice so to say)

I initialized an array with 5 values, then run this method which takes an array as a parameter, checks if an element is 0, if it is it assigns a random value between 1 and 6.

I've tried doing an enhanced for loop that looks at each element in the array, and theoretically if it is zero, it assigns a random integer between 1 to 6 to it.

public static void rollDice(int[] dice) {

for (int element: dice) {
    int roll = (int)(Math.random()*6) + 1;

    if (element == 0) {
        dice[element] = roll;
    }
}

My results are currently: [Random Number, 0, 0, 0, 0] My expected results are: [5 random integers]


Solution

  • This form of the Java for loop loops over the values, not the indexes, of the array. All of the values are 0 and you're using them as the index. You are setting the first element 5 times because of this.

    Use a traditional for loop.

    for (int index = 0; index < dice.length; index++) {
        // Your roll here
    
        dice[index] = roll;
    }