小编典典

从txt文件中检索随机单词,但没有输出,也没有编译器错误Java

java

我无法更改程序的外壳,最终目标是从txt文件中的单词列表中选择一个随机单词。我已经浏览了很多次,一次又一次地检查了代码,尝试了许多不同的事情,但是每次我运行它时,它都可以毫无问题地进行编译,但是我从未得到任何输出。我什至尝试在私有函数中插入一些输出,但无济于事。谁能看到我的代码有什么问题或可以向我解释发生了什么?

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());
      }
    }

阅读 164

收藏
2020-11-30

共1个答案

小编典典

构造函数扫描器(字符串源)实际上解析源字符串的内容,而不是将其视为文件名,您需要

new Scanner(new File(fileName))
2020-11-30