我不确定这是否可行。我正在构建一个程序来选择乐透行。我有一个 for 循环来随机选择从 1 到 35 的七个数字。我的计划是我可以制作一个 boolean 数组,然后取其中一个随机数在 boolean 数组中选择一个位置(不是值)并将其更改为真的。
通过这种方式,我得到了行号,并且我确信当数组位置为真时,该数字被采用。
import java.util.Random; {
public static void main(String[] args) {
int randomNr;
boolean[] lottoRow = new boolean[35];
Random randNr = new Random();
for(int i=0; i<7; i++) {
randomNr = randNr.nextInt(35)+1;
}
}
我该怎么做?它甚至是解决这个问题的好方法吗?
最佳答案
您可以为此使用array[index]
:
for (int i = 0; i < 7; i++) {
randomNr = randNr.nextInt(35) + 1;
lottoRow[randomNr - 1] = true;
}
这会将 lottoRow
的索引(您在问题中称它为 place)randomNr - 1
分配给 true
。请注意,我添加了 - 1
,因为数组是 0-indexed
。
关于java - 更改 boolean 数组中的值。选择地方而不是值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53516899/