我的项目开始于从文本文件导入数据并将其转换为ArrayList。我对ArrayLists不太熟悉,我不太清楚它是如何工作的。我已经提供了我的讲师提供的入门文件,看起来我需要使用缓冲读取器来导入文本文件。因为这门课程习惯提供入门代码而没有对该代码做什么的很好的解释,所以我也很欣赏一个缓冲式阅读器的简单解释,以及如果我有自己的话,我将如何自己创建。 这是打开时显示的文本文件:
manny 89 78 100 91 67
cindy 66 81 94 80 71
timmy 85 59 100 83 21
mikey 88 76 69 82 90
kelly 68 93 63 92 55
sandy 80 73 67 51 99
以下是入门代码:
import java.util.*;
import java.io.*;
public class ExamScores
{
public static void main( String args[] ) throws Exception
{
// close/reuse this file handle on the next file
BufferedReader infile = new BufferedReader( new FileReader( "ExamScores.txt" ) );
// you declare all needed ArrayLists and other variables from here on.
System.out.println("\nSTEP #1: 50%"); // 50%
System.out.println("\nSTEP #2: 25%"); // 75 %
System.out.println("\nSTEP #3: 10%"); // 85%
System.out.println("\nSTEP #4: 15%"); // 100%
} // END MAIN
// - - - - - - H E L P E R M E T H O D S H E R E - - - - -
} // END EXAMSCORES CLASS
一旦我创建了一个ArrayList,我该如何操作它来做一些事情,比如按字母顺序对名称进行排序。 ArrayList很像二维数组,或者该文本文件中的每一行都是一个单独的数组列表?为了创建我在这个项目中需要做的一切的想法,我必须按数组列表中的字母顺序对名称进行排序。然后我需要计算每个名字的平均分数,最后我需要考虑每个学生的第一,第三和第五次考试的平均值,并找出他们在这三个考试中的哪一个得分最低?我不是在寻求项目的确切答案,但我想提供所有关于我期望能够在这一点上与arraylist做什么的信息。谢谢。
答案 0 :(得分:1)
您可以使用java.io.BufferedReader
使用字符串填充ArrayList
BufferedReader inFile = new BufferedReader(new FileReader("ExamScores.txt"));
//Define and initialise the ArrayList
ArrayList<String> examScores = new ArrayList<String>(); //The ArrayList stores strings
String inLine; //Buffer to store the current line
while ((inLine = inFile.readLine()) != null) //Read line-by-line, until end of file
{
examScores.add(inline);
}
inFile.close(); //We've finished reading the file
//Loop through all elements in the list and output their values
for (int i=0; i < examScores.size(); i++)
System.out.println(examScores.get(i));
对ArrayList进行排序更加困难。对于您的程序,最好解析String并将值存储到自定义StudentExams类中。这是我为你制作原型的一个例子
public class StudentExams
{
private String studentName;
private int examScores[];
//Inline is the String we get from inFile.readLine();
public StudentExams(String inline)
{
//Pesudo-code
parse the string using String.split(" ");
store parsed values into studentName and examScores;
}
public String getStudentName()
{
return studentName;
}
public int[] getExamScores()
{
return examScores;
}
}
的文档
教程:How to use String#split(String regex)
我没有直接给你答案,但我已经给你足够的信息来自己拼凑答案。您可以阅读上述主题的所有教程。在互联网上有很多例子可以完全满足您的需求,您只需要尝试。