增强For循环不改变我的数组的所有元素[重复]

问题描述 投票:-2回答:4

这个问题在这里已有答案:

我目前正在开发一个程序,它将滚动5个骰子并为数组中的每个骰子存储一个随机数。我的问题是我的方法只是改变第一个元素,剩下的元素为0。 (只有滚动第一个骰子才能说)

我初始化了一个包含5个值的数组,然后运行此方法,该方法将数组作为参数,检查元素是否为0,如果是,则指定1到6之间的随机值。

我试过做一个增强的for循环来查看数组中的每个元素,理论上如果它是零,它会为它分配一个1到6之间的随机整数。

public static void rollDice(int[] dice) {

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

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

我的结果目前是:[随机数,0,0,0,0]我的预期结果是:[5个随机整数]

java arrays for-loop poker
4个回答
2
投票

这种形式的Java for循环遍历数组的值,而不是索引。所有的值都是0,你用它们作为索引。因此,您要将第一个元素设置为5次。

使用传统的for循环。

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

    dice[index] = roll;
}

1
投票

这里

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

你的代码说如果它是第一个元素,那么存储随机化的结果。由于其他元素不是第一个元素,因此在其他元素的情况下,条件将为假,因此不会存储卷。删除此如果:

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

0
投票
public static void rollDice(int[] dice) {

for (int i=0;i<dice.length;i++) {
    int roll = (int)(Math.random()*6) + 1;

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

您将索引0更改了5次,因为您将数组位置0的值作为要更改的索引


0
投票

dice[element]

element不是循环的索引,它是数组中元素的值。

在你的情况下,元素总是0因为java将0s放在新创建的数组中。

在这种情况下,您应该使用普通的for循环:

for (int i = 0; i < dice.length; i++) {
        int roll = (int) (Math.random() * 6) + 1;

        if (dice[i] == 0) {
            dice[i] = roll;
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.