Ok so, what I'm trying to do here is read strings from a file and put them in an array so I can randomly return one of the strings in the array. I believe I'm doing everything right except for actually constructing the array. The array is apparently constructing itself as {null, word in file at i}, {null, null, word in the file at i}, etc. In other words my failed attempt at creating this array in the end becomes {null, null, null, null, the last word in the file}. Essentially I'm thinking I need to initialize the array outside of the while loop, however I don't know how I can do this with what we've learned in class so far. A lot of forums say to use lists (haven't learned) or some other method that I'm not allowed to use because we haven't learned it yet. So any help would be appreciated. How can I read Strings from a file and convert them into an array so that I can return a random String from that array???
Here's where I'm at
Code:
public static String pickWord(String f) throws FileNotFoundException
{
Scanner file = new Scanner(new File(f));
String word = "";
Random ranWord = new Random();
int i = 0;
int ranInt = 0;
String[] wordChoices;
while (file.hasNextLine())
{
//I realize this initializes the array every time the loop runs which apparently sets the values in the array back to null. I need it not to do this,
//however I'm not sure how to get the length of the array outside of the loop. I've thought of finding it in a different while loop, but that doesn't
//work because the first while loop is the only one that runs.
wordChoices = new String[i+1];
wordChoices[i] = file.nextLine();
ranInt = ranWord.nextInt(i+1);
word = wordChoices[ranInt];
//used println to see what the array lookes like.
System.out.println(Arrays.toString(wordChoices));
i++;
}
//only printing to see what it actually returns
System.out.println(word);
return word;
}