从数组中获取随机值
我有一个简单的应用程序,可以生成事实 我想结合一个生成随机事实而不是递减递减的函数。
我的arrays看起来像这样。
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(int n)
( doc )和引用:
返回从此随机数生成器的序列中提取的伪随机,均匀分布的int值,介于0(包括)和指定值(不包括)之间。 nextInt的一般约定是伪随机生成并返回指定范围内的一个int值。 所有n个可能的int值都以(近似)相等的概率产生……
因此,您需要一个实际上是随机事实的随机数,因此在零和事实数组大小之间生成一个随机数:
例:
public String randomButton() { Random random = new Random(); return facts[random.nextInt(facts.length)]; }
简单! 方法nextInt(facts.length)
返回0和数组长度之间的随机整数。 将它作为数组的索引来获取随机数:
Random rnd = new Random() String randomFact = facts[rnd.nextInt(facts.length)];
试试这个吧
private Integer a = 0; public String randomButton() { Random random = new Random(); a = random.nextInt(facts.length); } String factNumber = facts.a;