Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random element from string array [closed]

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

like image 289
user1817558 Avatar asked Nov 12 '12 08:11

user1817558


1 Answers

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.

like image 135
amit Avatar answered Oct 02 '22 04:10

amit