Random element from string array [closed]

2019-01-18 08:55发布

I have a string array:

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)]);

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

1条回答
SAY GOODBYE
2楼-- · 2019-01-18 09:16

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. 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.

查看更多
登录 后发表回答