プログラムのシェルを変更することはできません。最終的な目標は、txt ファイル内の単語のリストからランダムな単語を選択することです。これを何度もスキャンし、コードを1つずつ調べ、さまざまなことを試しましたが、実行するたびに問題なくコンパイルされますが、出力は得られません。プライベート関数に出力を挿入しようとしましたが、役に立ちませんでした。誰かが私のコードの何が問題なのかを確認したり、何が起こっているのかを説明したりできますか?
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());
}
}