Steven Cassidy Steven Cassidy - 6 months ago 14
Java Question

Have to take words from a text file and copy them into ArrayList java?

Hi I am creating a hangman game and I have a class that is going to take words from a file each on its own line and copy them into an ArrayList one of the words will then be randomly chosen for the game. How do I copy the words so that it stores each individual line in the file as its own item in the ArrayList?

public class GameWord
{
private ArrayList <String> gameWords;
private String gameWord;
private String gameWord;

public GameWord()
{
gameWords = new ArrayList <String>();
/**code to copy words from file into ArrayList**/
Random random = new Random();
gameWord = gameWords.get(random.nextInt(gameWords.size()));
}
public String getGameWord()
{
return gameWord;
}
}

Answer

It's not as hard as you think (supposing one word, one line):

ArrayList<String> list = new ArrayList<>();

try (BufferedReader br = new BufferedReader(new FileReader(new File("input.txt")))) {
    String line;
    while ((line = br.readLine()) != null) {
       list.add(line);
    }
}   catch (IOException ex) {
    System.out.prinln(ex)
}

Start understanding the concept of reading file with BufferedReader, that uses FileReader. Check in the while-loop if there still exists a line, if so, read it and add to the ArrayList. Don't forget to wrap it all to try-catch. Finally you can work with your list.

To access the random word, use the Random class:

Random rnd = new Random();
String str = list.get(rnd.nextInt(list.size()));

The number of elements in your list is list.size. Take from that a random Integer number with rnd.nextint and call it as the parameter of getting an item from your list.

Comments