Random element from string array
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.
Admin
Updated on November 12, 2020Comments
-
Admin over 3 years
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
-
Avinash R over 9 yearsusing generics, it drills down to
private static <T> T randomFrom(T... items) { return items[new Random().nextInt(items.length)]; }