0

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

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);

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

4

1 回答 1

0

尝试这样做:

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);并仅参考地图。在地图中,您将按 lastKnownCategory 值对所有问题进行分组。

于 2013-09-20T18:54:21.097 回答