0

我正在处理一个文件并将其放入一个数组列表中。然后使用 String 类中的 split 方法创建一个带有格式化标记的数组列表。在我的测试器类中,它可以让我输入 line 或 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]);
        }


        }



}
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 回答