从数组中获得一个随机值 [英] Getting a random value from an array

查看:165
本文介绍了从数组中获得一个随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的阵列看起来像这样。

 公共类事实{
    字符串的事实[] = {大象不能跳的哺乳动物。
            蜡烛会燃烧时间更长,滴更少,如果它们被放置在冰箱使用前几个小时。
            土豆比人类更染色体。
            你燃烧更多的卡路里比睡觉你就看电视。
            那下蛋的动物没有肚脐。
    };字符串factNumber [] = {
            事实1
            事实2
            事实3
            事实4,
            事实5
};公共字符串randomButton(){
        随机R =新的随机();返回事实[I]
    }


解决方案

使用的 Random类,该类有一个方法,在 nextInt(INT N) DOC )和报价:


  

返回一个伪随机,0之间均匀分布的int值
  (含),并规定值(不包括),从此得出
  随机数生成器的序列。 nextInt的常规合同
  在指定范围内的一个整数值是伪随机地生成
  并返回。所有N个可能INT值的生成
  (大致)相同的概率...


所以,你需要一个随机数实际上是一个随机的事实,因此产生的零之间的事实数组大小的随机数:

例子:

 公共字符串randomButton(){
    随机随机=新的随机();
    返回事实[random.nextInt(facts.length)];}

I have a simple app that generates facts. I would like to incorporate a function that generates a random fact instead of incrementing of decrementing.

My array looks like this.

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]
    }

解决方案

use the random class, that class has a method, the nextInt(int n) (doc) and quote:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability...

so, you need a random number that is in fact a random fact, so generate a random number between zero and the facts array size:

Example:

public String randomButton() {
    Random random = new Random();
    return facts[random.nextInt(facts.length)];

}

这篇关于从数组中获得一个随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆