30

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

Laser
  • 6,652
  • 8
  • 54
  • 85
user1817558
  • 341
  • 1
  • 3
  • 5

1 Answers1

68

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.

amit
  • 175,853
  • 27
  • 231
  • 333
  • 7
    using generics, it drills down to `private static T randomFrom(T... items) { return items[new Random().nextInt(items.length)]; }` – Avinash R Sep 17 '14 at 21:07