gpt4 book ai didi

java - 我应该传递类里面的哪些信息才能获得所需的结果

转载 作者:行者123 更新时间:2023-12-01 14:05:41 24 4
gpt4 key购买 nike

我正在努力获取一个文件并将其放入数组列表中。然后使用 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]);
}


}



}

最佳答案

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

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

或者,你可以这样做:

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

关于java - 我应该传递类里面的哪些信息才能获得所需的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18927666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com