【问题标题】:Searching a file with two arrays使用两个数组搜索文件
【发布时间】: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,另一个是ScoreArrayList<Student>。另请注意,Java 中的变量通常用lowerCamelCase 编写。还请记住关闭阅读器,并且不要向 JVM 抛出异常。您可以(应该)在 finally {} 子句中关闭阅读器。

标签: java arrays file bufferedreader


【解决方案1】:

BufferedReader 实现了 AutoCloseable 并且从 1.7 开始可以自动关闭作为尝试的资源。 我同意 Emz 的观点,首先您应该将整个文件加载到内存中,然后再进行搜索。您可以使用签名Map<String,List<String>> 声明 hashMap,它作为键将有一个学生 ID,并作为所有分数的值。检索特定 studdentId 的分数将很快 map.get(studentId). 在循环中您可以读取尝试从文件中检索分数的输入,或者您可以将某些特定字符编码为主要功能的停止键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2022-11-26
    • 2014-11-28
    相关资源
    最近更新 更多