【发布时间】:2015-12-07 21:53:19
【问题描述】:
我有一个文件,我需要能够通过 ID 号搜索学生的文本文件,并通过这样做检索他们的分数。文本文件是这样设置的(长的数字是学生id,第二个是分数):
66440 63
50940 6
71394 18
84789 77
41527 60
86258 30
51632 59
等等。到目前为止,这是我拥有的代码。它还没有完成,我需要它来搜索第一个数组(学生)并检索第二个数组(分数):
public static void main(String[] args) throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new FileReader("scores.txt")))
{
String sCurrentLine;
String first = "Student ID: ";
String second = "Score: ";
while ((sCurrentLine = br.readLine()) != null) {
String[] information = sCurrentLine.split(" ");
String StudentID = information[0];
String Score = information[1];
Scanner input = new Scanner(System.in);
System.out.print("Enter a user ID: ");
String userID = input.nextLine();
if (StudentID = userID){
System.out.println(Score);
}
}}
}}
【问题讨论】:
-
逐行读取并由任意数量的空格和/或制表符分割。如有必要,将它们解析为
Integers。将它们存储在HashMap<Integer, Integer>中(其中第一个是StudentID,另一个是Score或ArrayList<Student>。另请注意,Java 中的变量通常用lowerCamelCase 编写。还请记住关闭阅读器,并且不要向 JVM 抛出异常。您可以(应该)在finally {}子句中关闭阅读器。
标签: java arrays file bufferedreader