0

I created an array with 100 elements in it and I am wondering how I can randomly select an element in the array and display the result that is contained within.

import java.util.ArrayList;
import java.util.Random;

public class slotMachine {

  Symbol[] slot1, slot2, slot3;

  public slotMachine() {
    // Generate a random element and state what it is
  }

  public void initSlots() {
    int i;
    //Slot 1
    slot1 = new Symbol[100];
    for (i = 0; i < 30; i++) {
      slot1[i] = Symbol.Bar;
    }
    for (; i < 60; i++) {
      slot1[i] = Symbol.Cherry;
    }
    for (; i < 80; i++) {
      slot1[i] = Symbol.Lime;
    }
    for (; i < 100; i++) {
      slot1[i] = Symbol.Seven;
    }
  }
}
dting
  • 38,604
  • 10
  • 95
  • 114
  • possible duplicate of [How to pick number from an integer array randomly in Java](http://stackoverflow.com/questions/8065532/how-to-pick-number-from-an-integer-array-randomly-in-java) – DavidW Apr 20 '15 at 21:31

1 Answers1

0

Math.random() is your answer. You can add following method to your class:

private int randomElement(Symbol[] array)
{
    int index = (int)(Math.random() * array.length);
    return array[index];
}

If you want to get uniformly distributed random integers, check out Random.nextInt().

mtyurt
  • 3,369
  • 6
  • 38
  • 57