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 {
br.readLine();
}
}
}
while(usedWord.contains(secretWord) || secretWord==null);
usedWord.add(secretWord);
return secretWord;
}