1

I've got this code, which (I hope) reads from a text file with 66 words and puts the words into an array.

BufferedReader buff = null;
String wordlist=new String[66];
int i=0;

try {
    buff = new BufferedReader(new FileReader("C:\\easy.txt"));
    wordlist[i] = buff.readLine();
    while(wordlist[i] != null&i<66){
        wordlist[i]=buff.readLine();
        i++;
    }
}

I want to pick a random word from the array. However trying a few things myself and looking at other questions doesn't seem to work. Any help would be appreciated

jww
  • 97,681
  • 90
  • 411
  • 885
Logger
  • 19
  • 1
  • 1
  • 2

5 Answers5

18

The simplest code IMHO would be:

String word = wordlist[new Random().nextInt(wordlist.length)];
Bohemian
  • 412,405
  • 93
  • 575
  • 722
3

This should work:

String randomString = wordlist[(int)(Math.random() * wordlist.length)];
David Koelle
  • 20,726
  • 23
  • 93
  • 130
  • 1
    I've learned since posting this answer about the difference between Math.random() vs. Random.nextInt(). http://stackoverflow.com/questions/738629/math-random-versus-random-nextintint – David Koelle Aug 06 '14 at 00:04
  • I'm not sure if this works. I've set it to display the word that it picked on a label and all it says "null". I've got all the code on the same button, so that possibly has something to do with it. Any suggestions? – Logger Aug 06 '14 at 02:38
  • This code definitely works. You might be having an issue if you're using a variable inside the action listener of your button that you have declared outside of your button, but without seeing your code, I cannot be sure. – David Koelle Aug 06 '14 at 22:53
0

Generate a random number between 0 and 65, and then use that number as the index of which String you choose.

Honinbo Shusaku
  • 1,411
  • 2
  • 27
  • 45
0

You can create a random number generator (an instance of Random).

Then you call the method nextInt(wordList.length) to get a random index on your array of string.

For example:

Random random = new Random(); int index = random.nextInt(wordList.length);

Then: wordList[index] to get the randomly selected string.

Phil
  • 3,375
  • 3
  • 30
  • 46
0

One solution is to is to select a random number from the wordlist array by doing
String = randomWord = wordlist[(int)Math.random() * wordlist.length]
or
String randomWord = wordlist[(int)Math.random() * 66]

Zavax
  • 59
  • 1
  • 2
  • 11