Search code examples
javadrjava

retrieving a random word from a txt file and getting no output, and no compiler error java


i cannot change the shell of the program, the end goal is to choose a random word from a list of words in a txt file. i've scanned through this many many times, gone through the code one by one, tried many different things, but every time i run it, it compiles without a problem but i never get any output. i've even tried inserting some output in the private functions, but to no avail. can anyone see what is wrong with my code or can explain to me what is happening?

import java.util.*;

    class PartOfSpeech
    {
      private String[] words;
      private Random random;
      private String filename;

      public PartOfSpeech(String filename)
      {
        this.filename = filename;
        this.read();
      }
      //this picks a random number and uses that number for the index of the array for which to return
      public String getRandomWord()
      {
        int index;
        index = random.nextInt(this.getCount());
        return words[index];
      }
      //this gets a count of how many lines of txt are in the file
      private int getCount()
      {
        Scanner fr = new Scanner(this.filename);
        int count = 0;
        while(fr.hasNextLine())
        {
         count++;
        }
       return count; 
      }
      //this creates a scanner and inserts each word from the txt file into an array
      private void read()
      {
        Scanner fr = new Scanner(this.filename);
        for(int i=0; i<this.getCount(); i++)
        {
         words[i] = fr.nextLine(); 
        }
      }

      public static void main(String[] args)
      {
        PartOfSpeech n = new PartOfSpeech("nouns.txt");
        System.out.print(n.getRandomWord());
      }
    }

Solution

  • Constructor Scanner(String source) actually parse the content of the source string, instead of treating it as a file name, You need

    new Scanner(new File(fileName))