Random element from an array of strings

I have a string array:

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

and I get a random element from this:

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

now I want to get the number in which the apple is present, when I press the button to get random fruits, for example, when I press the randon button, it gives me a Banana..and should also give me this element number 3

I get the item, but have a problem getting the item number, so please help me

+27
java android string arrays random
Nov 12
source share
1 answer

Just save the index generated in the variable, and then access the array using this variable:

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



PS I usually don’t like to generate a new Random object for each randomization - I prefer to use one Random in the program - and reuse it. This allows me to easily reproduce the problematic sequence if I later find an error in the program.

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

 int idx = r.nextInt(fruits.length) 

However, your approach is also fine, but it may be difficult for you to reproduce a certain sequence if you need further.

+64
Nov 12
source share



All Articles