-3
   String[] am = new String[10];

   am[0] = "Sam";
   am[1] = "Sam";
   am[2] = "Sam";
   am[3] = "Sam";
   am[4] = "Sam";
   am[5] = "Sam";
   am[6] = "Sam";
   am[7] = "Sam";
   am[8] = "Sam";
   am[9] = "Sam";

For a jeopardy game, random questions per GUI Jpanel button click

Magiichalo
  • 31
  • 5

1 Answers1

1

Approach 1: Shuffling the list

You can shuffle your list using:

List<String> list = Arrays.asList(am);
Collections.shuffle(list);

Even better is starting with an ArrayList, and adding your possibilites to that ArrayList, completely ignoring the String[] array

List<String> list = new ArrayList<String>();
list.add("value1");
list.add("value2");
...
Collections.shuffle(list);

You can then retreive an element from the shuffeled list using get(index), i.e. :

String random = list.get(0);

Approach 2: Randomizing the index

If you insist on using the String[]-array, you can do

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

This will create a Random-object, and generate a random integer ranging from 0 to the length of your array minus one. Once this integer is generated, it will be used as an index for to get an element from your String[]-array.

You can use the same approach on an ArrayList:

String random = list.get(new Random().nextInt(list.size));
Ad Fundum
  • 665
  • 6
  • 22