数组返回 null .. 生成随机词

Array returning null .. Generate random word

我正在尝试制作一个 class 来生成随机单词。到目前为止,我的选择是 ScannerBufferReader 我猜。 这是我认为最有效的代码,但是当我 运行 我得到 null.

public return randomWord getter 也会授予对 main class 中单词的访问权限吗?

    private static final String filepath = "/assets/words.txt";
    public String randomWord;
    public Random rand;
    private ArrayList<String> words = new ArrayList<String>();


    public void WordGenerator() {


        rand = new Random();
        String line;

        try {

            InputStream WordsFile = getClass().getResourceAsStream(filepath);
            BufferedReader br = new BufferedReader(new InputStreamReader(WordsFile));
            if(!br.ready()){
                System.out.println("No File");
            }
            else while ((line = br.readLine()) != null) {
                words.add(line);
            }
            br.close();
        }
        catch (IOException e) {
            System.out.println("Something is wrong");
        }

        int size = words.size();
        Random rn = new Random();
        int randWord = rn.nextInt(size);
        randomWord = words.get(randWord);
        System.out.println(randomWord);
    }
}

我认为您真正需要阅读文件的是删除 InputStream 行并将 BufferedReader 替换为以下行:

BufferedReader br = new BufferedReader(new FileReader(filepath));

因此您的代码将如下所示:

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

public class WordGeneratorClass
{
   private static final String filepath="../assets/words.txt";
   public String randomWord;
   public Random rand;
   private ArrayList<String> words=new ArrayList<String>();

   public void WordGenerator()
   {
        rand=new Random();
        String line;

        try
        {
           BufferedReader br = new BufferedReader(new FileReader(filepath));

           if(!br.ready())
           {
            System.out.println("No File");
           }
           else while((line=br.readLine())!=null)
           {
              words.add(line);
           }
           br.close();
        }
        catch (IOException e)
        {
           e.printStackTrace();
        }

        int size=words.size();
        Random rn=new Random();
        int randWord=rn.nextInt(size);

        randomWord=words.get(randWord);

        System.out.println(randomWord);
   }

   public static void main(String args[])
   {
      WordGeneratorClass gen = new WordGeneratorClass();
      gen.WordGenerator();
   }
}

确保您的 assets/words.txt 存在。

编辑
似乎问题也与您的 words.txt 的路径有关。上面的代码假定 assets/words/words.txt 与源代码位于同一目录中。更多信息,请查看here.