【问题标题】:Sorting a text file's info in Java using line.contains使用 line.contains 在 Java 中对文本文件的信息进行排序
【发布时间】:2012-11-02 04:10:58
【问题描述】:

我正在编写一个询问用户测验的程序。我必须阅读包含我需要的信息的文本文件。但是,我遇到了如何做到这一点的麻烦。我已经将尽可能多的问题分类到一个列表数组中,但其余的问题给我带来了麻烦。这是我必须使用的文本文件的格式:

(问题) (选项中的答案数) (x个选择) (尝试次数) (数字正确) (数字不正确)

我将如何使用我必须区分答案整数和统计整数的代码?

    Scanner fScan = new Scanner(new File(file_name));


    List<String> questions = new ArrayList<String>();
    List<String> other = new ArrayList<String>();
    int[] answers = new int[questions.size()];



    while (fScan.hasNextLine()) 
    {

        String line = fScan.nextLine();

    if (line.contains("?")) 
    {
        questions.add(line);

    } 
    else 
    {
        other.add(line);
    }
}

【问题讨论】:

  • 您的输入文件是什么样的?是(问题)(选项中的答案数量)(x 选项)(尝试的数量)(数量正确)(数量不正确)在同一行或不同行中
  • 来自here 我知道他们在不同的行。
  • 你能在不同的文件中保存统计整数和回答整数吗?最好的方法是使用数据库
  • 他们在不同的行,抱歉没有澄清
  • 只是附带说明,以下内容只是创建一个大小为零的数组 - int[] answers = new int[questions.size()];

标签: java indexof


【解决方案1】:

最好创建一个Map,其中问题为键,答案列表为值,例如下面:

Map<String, List<String>> questionAnswersMap = new HashMap<String, List<String>>();
List<String> answers = null;
while (fScan.hasNextLine()) {
   String line = fScan.nextLine();
   if (line.contains("?")){
      //new Question
      answers = new ArrayList<String>()
      questionAnswersMap.put(line, answers );
   }else{
      //answer of the previous question
      answers.add(line);
   } 
}

这里我假设问题和答案是按顺序写的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2010-10-18
    • 2023-04-09
    相关资源
    最近更新 更多