gpt4 book ai didi

java - java数组中不重复的随机数

转载 作者:行者123 更新时间:2023-12-03 01:07:41 25 4
gpt4 key购买 nike

我进行了搜索,但找不到问题的答案。我必须创建一个乐透类型的模拟,6 个号码 + 奖金号码,没有重复。我已经设法让它工作,但在 6 数字数组中,位置 [1] 处的数字始终为 0。我确信它很简单,但我对此是全新的,因此我们将感激地接受任何帮助.下面的代码,我确信它到处都是......

import java.util.Arrays;

public class Lotto {

public static void main(String[] args) {

int[] Lotto=new int[6];
final int MIN = 1;
final int MAX = 45;

for (int i = 0; i< Lotto.length; ++i)
{

Lotto [0] =MIN+ (int)(Math.random()*((MAX -MIN)+1));

while (Lotto[1] == Lotto[0])
{
Lotto[1] =MIN+ (int)(Math.random()*((MAX -MIN)+1));
}

while ((Lotto[2] == Lotto[0]) || (Lotto[2] == Lotto[1]) )
{
Lotto[2] = MIN+ (int)(Math.random()*((MAX -MIN)+1));

while ((Lotto[3] == Lotto[0]) || (Lotto[3] == Lotto[1]) || (Lotto[3] == Lotto[2]) )
{
Lotto[3] = MIN+ (int)(Math.random()*((MAX -MIN)+1));
}

while ((Lotto[4] == Lotto[0]) || (Lotto[4] == Lotto[1]) || (Lotto[4] == Lotto[2]) || (Lotto[4] == Lotto[3]) )

{
Lotto[4] = MIN+ (int)(Math.random()*((MAX -MIN)+1));



while ((Lotto[5] == Lotto[0]) || (Lotto[5] == Lotto[1]) || (Lotto[5] == Lotto[2]) || (Lotto[5] == Lotto[3])|| (Lotto[5] == Lotto[4]))

{
Lotto[5] = MIN+ (int)(Math.random()*((MAX -MIN)+1));
}


int[] BonusNumber=new int[1];
for (int j = 0; j< BonusNumber.length; ++j)
{

BonusNumber [j] =1+ (int)(Math.random()*((45 -1)+1));
}

System.out.println("Winner " + Arrays.toString(Lotto));
System.out.println("Bonus Number" +Arrays.toString(BonusNumber));
{


}
}
}
}
}
}

最佳答案

更改此循环:

while (Lotto[1] == Lotto[0])
{
Lotto[1] = random(MIN, MAX);
}

进入:

do {
Lotto[1] = random(MIN, MAX);
} while (Lotto[1] == Lotto[0]);

其余的代码也相应地。你看出问题出在哪里了吗?

但是在开始重写相当复杂且难以维护的代码之前,请检查一下这个实现,它更容易理解并且......正确:

final int MIN = 1;
final int MAX = 45;

final List<Integer> allPossible = new ArrayList<Integer>(MAX - MIN + 1);
for (int i = MIN; i <= MAX; ++i) {
allPossible.add(i);
}
Collections.shuffle(allPossible);
final List<Integer> lotto = allPossible.subList(0, 6);
int bonusNumber = allPossible.get(6);

System.out.println("Winner " + lotto);
System.out.println("Bonus Number" + bonusNumber);

Collections.shuffle()这里至关重要。

关于java - java数组中不重复的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14223422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com