gpt4 book ai didi

java - 使用 math.random 和 while 循环的简单 Java 彩票模拟器?

转载 作者:行者123 更新时间:2023-12-01 23:44:46 27 4
gpt4 key购买 nike

我如何格式化 while 循环来检查重复项,如果有重复项,则不返回该数字?

 import java.util.Scanner;

public class LotterySimulator
{
public static void main(String[] args)
{
final int POOL1 = 68;
final int POOL2 = 25;

long ball1, ball2, ball3, ball4, ball5, pball;

ball1 = Math.round(POOL1*Math.random()) + 1;
ball2 = Math.round(POOL1*Math.random()) + 1;
ball3 = Math.round(POOL1*Math.random()) + 1;
ball4 = Math.round(POOL1*Math.random()) + 1;
ball5 = Math.round(POOL1*Math.random()) + 1;
pball = Math.round(POOL2*Math.random()) + 1;

最佳答案

您可以使用 Set 集合来存储唯一值。方法add() 如果此集合尚未包含指定元素,则返回 true

例如:

    public static void main(String[] args) {
final int POOL1 = 68;
final int POOL2 = 25;

int i = 0;
Set<Long> ballSet = new HashSet<>();
while (i < 5) {
long ball = Math.round(POOL1 * Math.random()) + 1;

if (!ballSet.add(ball)) {
continue;
};
i++;
}
long pball = Math.round(POOL2 * Math.random()) + 1;
while (ballSet.contains(pball)) {
pball = Math.round(POOL2 * Math.random()) + 1;
}
String winner = ballSet.stream().map(Object::toString).collect(joining(", "));
System.out.println("Your winning numbers are: " + winner);
System.out.printf(" and the powerball is: %d", pball);
}
}

关于java - 使用 math.random 和 while 循环的简单 Java 彩票模拟器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58245270/

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