HashMap 混乱。 Reading/Writing 到文件。 Java

HashMap confusion. Reading/Writing to files. Java

到目前为止的代码:

public class test1 {                                                                                                           

public static void main(String[] args) throws IOException {                                                                
    //declare reader and writer                                                                                            
    BufferedReader reader = null;                                                                                          
    PrintWriter writer = null;                                                                                             

    //hash maps to store the data                                                                                          
    HashMap<String, String> names = new HashMap<String, String>();                                                         


    //read the first file and store the data                                                                               
    reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("IRStudents.txt"))));                   
    String line;                                                                                                           
    String[] arg;                                                                                                          

    while ((line = reader.readLine()) != null) {                                                                           
        if (!line.startsWith("-")) {                                                                                       
            arg = line.split(" ");                                                                                         


            names.put(arg[0], arg[1]);                                                                                     


        }                                                                                                                  
    }                                                                                                                      
    reader.close();                                                                                                        

//read the second file, merge the data and output the data to the out file
writer = new PrintWriter(new FileOutputStream(new File("File_2.txt")));
reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("Marks.txt"))));
while((line = reader.readLine()) != null){
    arg = line.split(" ");
    writer.println(arg[0] + " " + names.get(arg[0]));
    writer.println("Marks: " + arg[1]);
    writer.println("- - - - - -");
}                                                                          


        writer.flush();                                                                                                    
        writer.close();                                                                                                    
        reader.close();                                                                                                    
    }                                                                                                                      
} 

因此文本文件中的输出如下所示:

 25220 Fiona
 Marks: 68.3
 - - - - - -
 25212 Greg
 Marks: 70.5
 - - - - - -       

我有另一个文本文件,其中包含另一组标记,其布局与第一个标记文件相同。

现在我想向数据集添加一组新标记所以它应该如下所示:

 25220 Fiona
 Marks: 68.3  Marks2: 21.2
 - - - - - -
 25212 Greg
 Marks: 70.5  Marks2: 23.43
 - - - - - -         

那我能做些什么来补充呢?我假设我必须为新的文本文档添加一个新的哈希图?但是当我尝试做所有这些时,它从来没有完全奏效。

IR 学生:

25987 Alan
25954 Betty
25654 Chris
25622 David                                                                                                      

添加新标记时,使用此方法将它们添加到现有标记中:

String key = arg[0];
String secondMarks = arg[1];

String theMarks = names.get(key);
theMarks = theMarks + " Marks2: " + secondMarks;
names.put(key, theMarks);

我想我理解你的问题,如果这不正确请告诉我。

要求是将此人收到的所有标记都放在自己的行上...

System.out 流中有两个打印函数。

打印和 println

arg = line.split(" ");
writer.println(arg[0] + " " + names.get(arg[0]));

writer.print("Marks: " + arg[1]);
for(int i = 2; i < args.length; i++){
    writer.println(" Marks" + i + ": " + arg[i]);
}

writer.println("\n- - - - - -");

我认为您对字符串的操作太多了。如果您将有更多标记的文件以类似方式处理,则字符串操作可能会增加,这可能会降低您的代码的可读性,并可能为错误提供更多空间。我认为以下是更好的方法。

您可以创建具有以下结构的 MarksRecord class。

public class MarksRecord {
   private String subject; // or whatever this variable name should be.
                           // in your case it should hold value marks1.
   private double marks;

}

同样,您可以创建一个不可变的 Student/similar class,如下所示。这可能是一个值 class,它具有基于您在每个文件中读取的第一个数字的 equals 和 hashCode 方法。我猜是卷号或类似的东西可以以独特的方式识别学生。

public final class Student {
    private final String rollNumber;
    private final String name;

    // equals, hashCode, and other methods.
}

然后在你的主要方法中你可以有一个

Map<Student, ArrayList<MarksRecord>>

。或者你也可以使用

Map<String, ArrayList<MarksRecord>>

其中第一个字符串是学生记录的卷号。

这样每次您有一个新的标记文件时,您的数据结构就能够容纳它。

您也可以执行以下操作。

package toBeDeleted;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class MarksProcessor {


    private final Map<String, Record> map = new HashMap<>();

    public static void main(String[] args) {
        String fileName = "file1.txt"; // change it to your specific file.
        MarksProcessor marksProcessor = new MarksProcessor();
        marksProcessor.processFile(fileName, 0);
        fileName = "file2.txt";
        marksProcessor.processFile(fileName, 1);
        marksProcessor.writeData();

    }

    private void processFile(String fileName, int marksIndex) {
        try(/*specify your reader resources here*/) {
            // read the first record and get rollNumber, name and marks.
            String roll = "valueYouGot";
            double value = 0.0; // the value you read.
            Record record = map.get(roll);
            // if record is null, you need to create one
            // and put it into the map.
            //record.updateMarks(marksndex, value);
        }
    }

    private void writeData() {

        // if this needs to be written to a file/stream, create a writer.
        for (Map.Entry<String, Record> entry : map.entrySet()) {
            String roll = entry.getKey();
            Record record = entry.getValue();
            if (record != null) {
                String name = record.getName();
                double marks1 = record.getMarks(0);
                double marks2 = record.getMarks(1);
                // Now you have all the values. Print them 
                // however you like. Wherever you like.
            }
        }
    }

    static class Record {
        private String name;
        private double[] marks = new double[2];


        Record(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public double getMarks(int index) {
            if (index < 0 || index > 1)
                throw new IllegalArgumentException("index should be 0 or 1 but"
                        + " the supplied index was " + index);
            return marks[index];
        }
        public void updateMarks(int index, double value ) {
            if (index < 0 || index > 1)
                throw new IllegalArgumentException("index should be 0 or 1 but"
                        + " the supplied index was " + index);
            marks[index] = value;
        }


        @Override
        public String toString() {
            return "the way you want to type your output";
        }

    }


}