Reputation: 185
I have a text file that contains a list of films:
Kangaroo Jack
Superman
Shawshank Redemption
Aladdin
What I want to do is pass all of these films into an array and then randomly select a film from the array. However it seems to always select 'Aladdin' and I am not sure what I am doing wrong? How can I randomly select films from the array?
public static void main(String[] args) throws FileNotFoundException {
String[] movieList = {};
File file = new File("xxx\\listofmovies.txt");
Scanner fileScanner = new Scanner(file);
Scanner scanner = new Scanner(System.in);
Random random = new Random();
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
// Reads the whole file
movieList = line.split("//s");
//splits the string by white space characters meaning we will get the full word(s) per line
}
boolean weArePlaying = true;
while (playing) {
char[] randomWordToGuess = movieList[random.nextInt(movieList.length)].toLowerCase().toCharArray();
int wordLength = randomWordToGuess.length;
char[] playerGuess = new char[wordLength];
boolean wordCompleted = false;
...
}
Upvotes: 0
Views: 59
Reputation: 124
movieList = Line.Split("//")
This line is always overwriting movielist with the last line in the file: Alladin
Rather write it like the following:
ArrayList<String> movieList = new ArrayList<>();
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
movieList.add(line);
}
It's important to note that your original approach would have succeeded if all the movie names were on the same line and had no white spice in between their names like this:
KangarooJack Superman ShawshankRedemption Aladdin
loop also wouldn't have been necessary. So it could have been written like this:
String[] movieList = {};
String line = fileScanner.nextLine();
movieList = line.split("//s");
And if you want to get really wild...
String[] movieList = fileScanner.nextLine().split("//");
Upvotes: 1
Reputation: 347234
movieList = line.split("//s");
is only assigning the last movie to the array, so there is only ever one element in the array. Instead, you need to read each line and assign it to an entry in the array.
Maybe something more like...
String[] movieList = new String[4];
File file = new File("xxx\\listofmovies.txt");
Scanner fileScanner = new Scanner(file);
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int index = 0;
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
movieList[index] = line;
index++;
}
This assumes that there are only 4 lines in the file, if there aren't then you will have IndexOutOfBoundsException
.
You could guard against this in a number of ways. You could put the number of expected lines as the first line of the file and then create the array based on that or you could exit the while-loop
when the array is full or you could use a ArrayList
, which is a type of dynamic array
Upvotes: 0