从Java中的字符串数组采摘的随机项目 [英] Picking a random item from an array of strings in java

查看:110
本文介绍了从Java中的字符串数组采摘的随机项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字符串数组的一些,我想从每个阵列随机选择一个项目。我怎样才能做到这一点?

下面是我的数组:

 静态最终的String [] =结合{和,或,但是,因为};静态最后的String [] = proper_noun {弗雷德,简,尼克松,美国小姐};静态最后的String [] = common_noun {男人,女人,鱼,大象,麒麟};静态最后的String [] =确定{A,中,每一个,一些};静态最后的String []形容词= {大,微小,pretty,光头};静态最后的String [] = intransitive_verb {跑,跳,讲座,睡觉};静态最后的String [] = transitive_verb {爱,恨,看见,知道,寻找,发现};


解决方案

使用的 Random.nextInt(INT) 方式:

 最终的String [] = proper_noun {弗雷德,简,尼克松,美国小姐};
随机随机=新的随机();
INT指数= random.nextInt(proper_noun.length);
的System.out.println(proper_noun [指数]);

这code不是完全安全的:一次出四它会选择尼克松

要引用一个文档 Random.nextInt(INT)


  

返回一个伪随机,0之间均匀分布的int值
  (含)和指定值(不包括)


在你的情况传递一个数组的长度到 nextInt 会做的伎俩 - 你会得到范围 [0随机数组索引; your_array.length)

I have some arrays containing Strings and I would like to select randomly an item from each array. How can I accomplish this?

Here are my arrays:

static final String[] conjunction = {"and", "or", "but", "because"};

static final String[] proper_noun = {"Fred", "Jane", "Richard Nixon", "Miss America"};

static final String[] common_noun = {"man", "woman", "fish", "elephant", "unicorn"};

static final String[] determiner = {"a", "the", "every", "some"};

static final String[] adjective = {"big", "tiny", "pretty", "bald"};

static final String[] intransitive_verb = {"runs", "jumps", "talks", "sleeps"};

static final String[] transitive_verb = {"loves", "hates", "sees", "knows", "looks for", "finds"};

解决方案

Use the Random.nextInt(int) method:

final String[] proper_noun = {"Fred", "Jane", "Richard Nixon", "Miss America"};
Random random = new Random();
int index = random.nextInt(proper_noun.length);
System.out.println(proper_noun[index]);

This code is not completely safe: one time out of four it'll choose Richard Nixon.

To quote a documentation Random.nextInt(int):

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

In your case passing an array length to the nextInt will do the trick - you'll get the random array index in the range [0; your_array.length)

这篇关于从Java中的字符串数组采摘的随机项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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