gpt4 book ai didi

java - 从数组列表创建数组列表

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

我有一个通过导入文件创建的数组列表。我现在想按类别将此列表分成更小的数组列表。我的原始数组列表的代码如下:

public class TriviaGamePlayer {

public static void main(String[] args) throws IOException {
File gameFile = new File("trivia.txt");

List<TriviaGame> triviaQuestions = new ArrayList<TriviaGame>();
Scanner infile = new Scanner(gameFile);
String lastKnownCategory = "";

while (infile.hasNextLine()) {
String currentLine = infile.nextLine();

if (!currentLine.isEmpty()) {
TriviaGame currentQuestion = new TriviaGame();

if (currentLine.endsWith("?")) {
currentQuestion.setCategory(lastKnownCategory);
currentQuestion.setQuestion(currentLine);
currentQuestion.setAnswer(infile.nextLine());
} else {
currentQuestion.setCategory(currentLine);
currentQuestion.setQuestion(infile.nextLine());
currentQuestion.setAnswer(infile.nextLine());
lastKnownCategory = currentLine;
}
triviaQuestions.add(currentQuestion);
}
}

infile.close();



System.out.println(triviaQuestions);

这将显示[类别=艺术与文学,问题=邦戈鼓传统上放在什么之间进行演奏?,答案=膝盖]在不同的类别中还有更多。从这里我想为每个类别创建不同的数组列表,并能够挑选出类别、问题和答案。谢谢

最佳答案

尝试这样做:

public class TriviaGamePlayer {

static class TriviaGame {
String category;
String question;
String answer;
}

public static void main(String[] args) throws IOException {
File gameFile = new File("trivia.txt");

List<TriviaGame> triviaQuestions = new ArrayList<TriviaGame>();
Scanner infile = new Scanner(gameFile);
String lastKnownCategory = "";
Map<String, List<TriviaGame>> map = new HashMap<String, List<TriviaGame>>();

while (infile.hasNextLine()) {
String currentLine = infile.nextLine();

if (!currentLine.isEmpty()) {
TriviaGame currentQuestion;
if(map.containsKey(lastKnownCategory) == false)
map.put(lastKnownCategory, new ArrayList<TriviaGame>());

map.get(lastKnownCategory).add(currentQuestion = new TriviaGame());

if (currentLine.endsWith("?")) {
currentQuestion.setCategory(lastKnownCategory);
currentQuestion.setQuestion(currentLine);
currentQuestion.setAnswer(infile.nextLine());
} else {
currentQuestion.setCategory(currentLine);
currentQuestion.setQuestion(infile.nextLine());
currentQuestion.setAnswer(infile.nextLine());
lastKnownCategory = currentLine;
}
triviaQuestions.add(currentQuestion);
}
}

infile.close();

System.out.println(map);
}
}

基本上,您甚至可以删除 triviaQuestions.add(currentQuestion); 并仅引用 map 。在 map 中,您将按 lastKnownCategory 值对所有问题进行分组。

关于java - 从数组列表创建数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18923724/

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