我目前正在参加我的第一个java课程并且完全陷入了练习。我应该从包含学生ID及其相应考试成绩的文本文件中读取数据,让程序评分,然后打印结果。
我有点理解这个问题,但我们正在努力的这本书有点难以阅读。这一切都在一起模糊,我觉得他们希望我阅读两个不同的东西,并在如何将它们组合在一起进行合理的飞跃,而我却无法得到它。
TTFTFTTTFTFTFFTTFTTF ABC54102 T FTFTFTTTFTTFTTF TF DEF56278 TTFTFTTTFTFTFFTTFTTF ABC42366 TTFTFTTTFTFTFFTTF ABC42586 TTTTFTTT TFTFFFTF
我的主要问题是我不知道如何将数组与我拥有的数据联系起来。
答案 0 :(得分:3)
我不会发布整个解决方案,但会给出一些步骤。
请按照此示例
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
答案 1 :(得分:0)
所以,由于你的T&F和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);
}