gpt4 book ai didi

java - 从数组中获取随机值

转载 作者:行者123 更新时间:2023-12-01 18:05:26 25 4
gpt4 key购买 nike

我有一个可以生成事实的简单应用程序。我想合并一个生成随机事实而不是递增或递减的函数。

我的数组看起来像这样。

public class Facts {
String facts[] = {
"Elephants are the only mammals that can't jump.",
"Candles will burn longer and drip less if they are placed in the freezer a few hours before using.",
"Potatoes have more chromosomes than humans.",
"You burn more calories sleeping than you do watching television.",
"Animals that lay eggs don't have belly buttons.",
};

String factNumber[] = {
"Fact 1",
"Fact 2",
"Fact 3",
"Fact 4",
"Fact 5",
};

public String randomButton() {

Random r = new Random();
return facts[i]
}

最佳答案

简单!方法 nextInt(facts.length) 返回 0 到数组长度之间的随机整数。将其作为数组的索引即可获取随机数:

Random rnd = new Random()
String randomFact = facts[rnd.nextInt(facts.length)];

关于java - 从数组中获取随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825021/

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