0

私はファイルを取り、それを配列リストに入れることに取り組んでいます。次に、String クラスの split メソッドを使用して、フォーマットされたトークンで配列リストを作成します。私のテスタークラスでは、行またはnullに入れることができます。Null は何もせず、line は 3 つのフィールドすべてに最初のトークンを入力します。while ループで正しい情報を取得できません。クラスコンストラクターで探しているものを取得するには、そこに何を渡す必要がありますか? これが私のコードです。

public class TriviaGame {
   String category;
   String question;
   String answer;




public TriviaGame(String category, String question, String answer) {
    super();
    this.category = category;
    this.question = question;
    this.answer = answer;
}





@Override
public String toString() {
    return "TriviaGame [category=" + category + ", question=" + question
            + ", answer=" + answer + "]";
}





/**
 * @return the category
 */
public String getCategory() {
    return category;
}





/**
 * @param category the category to set
 */
public void setCategory(String category) {
    this.category = category;
}





/**
 * @return the question
 */
public String getQuestion() {
    return question;
}





/**
 * @param question the question to set
 */
public void setQuestion(String question) {
    this.question = question;
}





/**
 * @return the answer
 */
public String getAnswer() {
    return answer;
}





/**
 * @param answer the answer to set
 */
public void setAnswer(String answer) {
    this.answer = answer;
}





}

次にテスター

import java.io.File;
import java.io.IOException;
import java.util.Scanner;


public class TriviaGameTester2 {

/**
 * @param args
 */
public static void main(String[] args) throws IOException {
    File dataFile = new File ("trivia.txt");

    Scanner infile = new Scanner(dataFile);
        String line;
        String [] words;
        TriviaGame [] games;
        final int NUM_QUESTIONS = 300;
        int counter;
        TriviaGame temp;

        games = new TriviaGame[NUM_QUESTIONS];

        counter = 0;


        while(infile.hasNext()){
            line = infile.nextLine();
            words = line.split("[,]");


            temp = new TriviaGame(null, null, null);
            //what should I put here to get my categories, questions
                            //and answers?
            games[counter] = temp;
            counter++;

        }

        infile.close();

        for(int i = 0; i < counter; i++){
            System.out.println(games[i]);
        }


        }



}
4

1 に答える 1

0

コード行は、カテゴリ、質問、および回答をファイルに追加した順序によって異なります。ファイルの各行がカテゴリ、質問、回答であるとすると、コードは次のようになります。

temp.setCategory(words[0]);
temp.setQuestion(words[1]);
temp.setAnswer(words[2]);

または、次のようにすることもできます。

temp = new TriviaGame(words[0], words[1], words[2]);
于 2013-09-21T00:35:12.277 に答える