我将通过课程中的哪些信息来获得所需的结果

时间:2013-09-21 00:24:18

标签: java arrays

我正在制作一个文件并将其放入arraylist。然后使用String类中的split方法生成带有格式化标记的arraylist。在我的测试器类中,它允许我放入行或null。 Null不执行任何操作,并且line在所有三个字段中输入第一个标记。我不能得到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]);
        }


        }



}

1 个答案:

答案 0 :(得分:1)

代码行取决于您添加文件的类别,问题和答案的顺序。假设文件中的每一行都是:category,question,answer,您的代码将是:

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

或者,您可以这样做:

temp = new TriviaGame(words[0], words[1], words[2]);