I am creating a hangman game for my school summative. However I have been experiencing some difficulties with one of my methods called Random Words which performs a few tasks for my program including:

  • Generates a random word from a file which contains 6 different words
  • Does not generate the same random word twice. (this is part I'm having difficulties with).

This program works fine however it randomly stops in the middle returning secretWord as null even when there are still words left in my Words file.

Can anyone please help me please and thank you.

ps: A lot of people asked me why I have || secretWord==null in my do while statement and the reason I have that is because my program was giving me a null exception error and this prevents this from happening.

What I have tried:

public static String RandomWord() throws IOException {      
        FileReader fr = new FileReader ("./Hang Man File/Words.txt");           
        BufferedReader br = new BufferedReader(fr);                             
        int random = 0;
        String secretWord =" ";
        do {
            random =(int) ((int) 1+(Math.random()*6));
            for (int lineNo = 1; lineNo < 10; lineNo++) {
                if (lineNo == random) {
                     secretWord = br.readLine();
                else {
        while(usedWord.contains(secretWord) || secretWord==null); 

        return secretWord;

"Does not generate the same random word twice."

Consider an array the size equal to the number of words. Start with.

  1. The array with the number 1 in array location 1 and so on till the end.
  2. Now shuffle the array. (Google shuffle an array for many prior discussions.)

For each game you increment a game counter and that is used to look up the next random word and there will be no duplicates.
Test for when you've exchausted your word count and then your choice to repeat step 1 and 2 or start at position 1.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.