从字符串数组随机元素 [英] Random element from string array

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

问题描述

我有一个字符串数组:

String[] fruits = {"Apple","Mango","Peach","Banana","Orange","Grapes","Watermelon","Tomato"};

和我收到的随机元素从这个方式:

and i am getting random element from this by:

String random = (fruits[new Random().nextInt(fruits.length)]);

现在我想在这苹果是present当我按下按钮来获得随机水果的数量,就像当我preSS randon按钮,它给了我Banana..and也应该给我的元素号码是 3

now i want to get the number at which apple is present when i hit the button to get random fruit, like when i press randon button it gives me Banana..and also should give me that element number is 3

我得到的元素,但有问题,得到元素数目,所以请帮助我

I get the element but have problem getting the element number, so please help me out

推荐答案

只是存储在一个变量生成的索引,然后使用该varaible访问数组:

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);


P.S。我平时不喜欢每randoization产生新的随机对象 - 我在使用单个随机 preFER方案 - 并重新使用它。它可以让我轻松地再现问题的顺序,如果我以后发现程序中的错误。


P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

根据这种方法,我都会有一些变量随机ř的地方,我将只使用:

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

不过,你的做法是正常的,但是你可能很难再现特定的顺序,如果你需要稍后。

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

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

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