gpt4 book ai didi

java - 如何随机化一个数组以便一次打印 x% 的值?

转载 作者:行者123 更新时间:2023-12-01 17:43:23 24 4
gpt4 key购买 nike

我正在尝试用java制作一个简单的老虎机。但是我不知道如何随机化数组,以便一次返回 x% 的数组的某个值。

例如,对于下面的代码,我想随机化结果,假设 Fish 将返回 40%,Dragon 将返回 30%,Joke 将返回 25%,Jackpot 将返回 5%。

public class SlotMachine{
public static void main(String args[]){
String array[] = {"Fish", "Dragon", "Joker", "Jackpot"};
}
}

最佳答案

只需生成一个 0 到 1 之间的随机数,然后根据您想要的逻辑选择一个数组元素:

double rand = Math.random();
String choice;
if (rand < 0.05) {
choice = array[3];
}
else if (rand < 0.30) {
choice = array[2];
}
else if (rand < 0.60) {
choice = array[1];
}
else {
choice = array[0];
}

System.out.println(choice);

关于java - 如何随机化一个数组以便一次打印 x% 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58219259/

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