0

プログラムのシェルを変更することはできません。最終的な目標は、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());
      }
    }
4

5 に答える 5

1

構造を再考することをお勧めします。ファイルに含まれる単語の数がわからないため、複数回の繰り返しを避けるために、Collection<String>固定された ではなく、おそらく a を使用する必要があります。String[]おそらく、次のようなことを試すことができます。

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class PartsOfSpeech {

    private final List<String> words;
    private final File file;

    private int index;

    public PartsOfSpeech(final String filePath){
        words = new LinkedList<>();

        file = new File(filePath);
        read();

        Collections.shuffle(words);
    }

    private void read(){
        try{
            final Scanner input = new Scanner(file, "UTF-8");
            while(input.hasNextLine())
                words.add(input.nextLine());
            input.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public String getRandomWord(){
        if(index == words.size()){
            index = 0;
            Collections.shuffle(words);
        }
        return words.isEmpty() ? null : words.get(index++);
    }

    public static void main(String[] args){
        final PartsOfSpeech pos = new PartsOfSpeech("noun.txt");
        System.out.println(pos.getRandomWord());
    }
}
于 2014-02-07T05:43:50.947 に答える
1

Constructor Scanner(String source) は実際にソース文字列の内容を解析します, ファイル名として扱うのではなく, 必要です.

new Scanner(new File(fileName))
于 2014-02-07T05:32:33.157 に答える
0

ファイルを文字列のリストに一度だけ読み込むことをお勧めします。count メソッドは単にリストで size() を呼び出すだけです。ファイルを読み取り、文字列のリストに解析するために使用できるメソッドを次に示します。

    public List<String> readFile(String filePath) throws IOException {
    List<String> result = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                    new FileInputStream(filePath)))) {
        String line;
        while ((line = reader.readLine()) != null) {
            result.add(line.replace("\n", ""));
        }
    }

    return result;
}
于 2016-02-02T19:59:54.160 に答える
0
  1. インスタンス変数 random が初期化されていないため、NPE が発生します。
  2. 他の人が提案したように、 new File(this.filename) を使用してください。
  3. Scanner.next() を呼び出さなかったため、getCount メソッドは無限ループに陥っています。
  4. 他の人が提案したようにコレクションオブジェクトを使用してください。
  5. カウントを取得する必要があるたびに、リスト全体をループする必要はありません。
  6. インスタンス変数の使用を最小限に抑えるか、完全に回避することをお勧めします。
于 2014-02-07T06:07:29.740 に答える