【问题标题】:Processing data from a text file into an array [closed]将文本文件中的数据处理到数组中[关闭]
【发布时间】:2015-01-22 14:51:00
【问题描述】:

我目前正在上我的第一个 Java 课程,并且完全沉浸在练习中。我应该从包含学生 ID 及其相应考试成绩的文本文件中读取数据,让程序对它们进行评分,然后打印结果。

我有点理解这个问题,但我们正在研究的这本书有点难读。这一切都模糊不清,我觉得他们希望我阅读两篇不同的东西,并在如何将它们放在一起方面做出合乎逻辑的飞跃,我就是不明白。

TTFTFTTTFTFTFFTTFTTF ABC54102 T FTFTFTTTTFTTFTTF TF DEF56278 TTFTFTTTTFTFTFFTTFTTF ABC42366 TTFTFTTTTFTFTFFTTF ABC42586 TTTTFTTT TFTFFFTF

我的主要问题是我看不到如何将数组与我拥有的数据联系起来。

【问题讨论】:

  • 文本文件必须有某种分隔符,比如它可能是 csv 文件或其他东西。没有你发布就无法判断。但是读入文件,并且对于每一行,拆分任何分隔符,通过其列索引获取分数、ID等。
  • 学习如何编程的开始是知道谷歌正确的事情。显然你不这样做,我建议你进行以下搜索:“如何逐行读取文件 java”,“如何在逗号 java 上拆分字符串”(或者在给定的文件中将内容分开) .您可能应该对从文件中读取的内容进行对象表示,并将它们存储在数组列表中。诚实地编辑您的帖子以显示文件的外观我可以进一步帮助您

标签: java arrays text


【解决方案1】:

我不会发布整个解决方案,但会给出一些开始的步骤。

按照这个例子

BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
ArrayList<String> array = new ArrayList<>();
while ((line = reader.readLine()) != null) {
    array.add(line);
}

并像这样拆分字符串

str.split(" "); // considering that ids and name are separated by spaces

【讨论】:

  • 看,但这就是我感到困惑的地方。我在该主题上查找的所有内容都开始抛出有关拆分字符串或执行 x 或 y 的内容,而这本书没有提到任何内容。
  • 觉得我的回答有用吗?如果是,则将其标记为正确。谢谢
  • 缓冲阅读器到底是什么?我可以请一些 cmets 详细说明每个步骤的具体作用吗?
  • 简单来说,BufferedReader 用于 I/O,即读取和写入文件。详情在这里stackoverflow.com/questions/15984789/…
  • 再一次,我不知道从哪里开始。这是一个该死的兔子洞。我最终遇到的问题比我开始时要多,而且这本书在浏览各种术语的四五个定义然后使用它们就像我不知道它们的意思一样时也无济于事。
【解决方案2】:

因此,由于您的 T 和 F 列表中允许使用空格,我认为这意味着学生将问题的答案留空,因此您无法使用split 之类的便捷方法轻松地将答案。相反,我们使用我们的知识,即问题的数量必须相同,并且 id 的长度必须相同。您可以使用 substring 方法解析出您需要的内容。

这是一些伪代码:

final int NUM_QUESTIONS = 25; //I didn't actually count, that's your job
final int ID_LENGTH = 8;
int currentIndex = 0;

//assuming you can fit the whole string in memory, which you should in an intro java class
//do the operations that googling "read a file into a string java" tells you to do in readFileToString
String fileContents = readFileToString("saidFile.txt");


while(fileContents.charAt(currentIndex) != fileContents.length()){
    String userAnswers = fileContents.substring(currentIndex, currentIndex+NUM_QUESTIONS);

    //move index past userAnswers and the space that separates the answers and the id
    currentIndex = currentIndex + NUM_QUESTIONS + 1;

    String userId = fileContents.substring(currentIndex, currentIndex+ID_LENGTH)

    //move currentIndex past userId and the space that separates the userId from the next set of answers
    currentIndex = currentIndex + ID_LENGTH + 1;

    //either create an object to store the score with the userId, or print it right away
    int score = gradeAnswers(userAnswers)
    System.out.println(userId + " scored " + score);
}

【讨论】:

    猜你喜欢
    • 2023-01-18
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    相关资源
    最近更新 更多