Print random line from text file in java

I am new to java and for a class I am supposed to create a hangman style game. First I am just trying to pull a random word from a txt file, however when I run the following code it just prints the full list. Any suggestions? My teacher advised we cannot use arrays, we have to get a random int, then use it with nextLine to get the random word…

Also, ignore the random stated variables, thats for later in the assignment, but don’t want to ask on that unless needed later!

import java.util.Scanner;
import java.util.Random;
import java.io.*;

public class WordGame {

static Random randomNum = new Random();

   public static void main(String[] args) throws IOException
   {
   
   int numberGames = 1;
   int highScore;
   int avgScoreRunning;
   int avgScoreFinal;
   int currentScore;
   String secretWordFinal = "";
   
   System.out.print("Welcome to Words: The Word Guessing Game!n");
   System.out.print("Play as many games as you like. I'll remember your top score.n");
   System.out.println("and also compute your average for all games played.");
   
   findWord(secretWordFinal);
   }
      public static void findWord(String secret) throws IOException
      {
   
      File wordList = new File("wordlist.txt");
      Scanner wordListNew = new Scanner(wordList);
   
      int wordNumber = randomNum.nextInt(33735) +1;   
            
      for(int i = 1; i <= wordNumber;){
            if(i < wordNumber){
            i++;
            }
            else if (i == wordNumber){
            String secretWord = wordListNew.nextLine();
            System.out.println(secretWord);
            }

Answer

The answer boils down to your for loop condition and when you are calling nextLine().

Starting off with nextLine(), you are currently only calling nextLine() when you reach the numbered line you want. However, you need to advance the “pointer” in the file to reach that line as well, otherwise, you will only read the first line of the file when you call it. This is compounding with the next issue though:

Second, because your for loop condition is i <= wordNumber, you are continuing to loop when you finally do get to that line number, but because you don’t increment i again once you reach the number you want (you don’t have i++ inside your else if code), it is always evaulating to true (i == wordNumber) and keeps looping. You can see below I’ve put the incrementing of i into the third position of the for loop so that it always increments.

for(int i = 1; i <= wordNumber; i++){
    String secretWord = wordListNew.nextLine();
    if (i == wordNumber){
        System.out.println(secretWord);
    }
}