我无法更改程序的外壳,最终目标是从 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());
}
}