Использование HashMaps с чтением / записью текстовых файлов - Незначительное исправление

1

Код:

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>();
    HashMap<String, String> names1 = 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("IR101.txt"))));
        while((line = reader.readLine()) != null){
            arg = line.split(" ");
            writer.println(arg[0] + " " + names.get(arg[0]));
            writer.println("Marks: " + arg[1] + "    Marks2:");
            writer.println("- - - - - -");    }

              //read the third, 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("IR102.txt"))));
               while((line = reader.readLine()) != null){
                   arg = line.split(" ");
                   writer.println(arg[0] + " " + names.get(arg[0]));
                   writer.println("Marks: "  + "    Marks2:" + arg[1]);
                   writer.println("- - - - - -");    }


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

}

Так что этот код делает до сих пор, читается из текстового файла, сохраняет/форматирует его и записывает в новый текстовый файл.

Выходной текстовый файл выглядит примерно так:

25987 Alan
Marks:     Marks2:20.7
- - - - - -
25954 Betty
Marks:     Marks2:63.4
- - - - - -
25218 Helen
Marks:     Marks2:53.4
- - - - - -

Теперь это правильный путь, кроме знаков. Каждый ученик имеет две разные метки, которые хранятся в разных текстовых файлах. Я хочу импортировать информацию о знаках из обоих текстовых файлов и выводить их в один текстовый файл.

Код получает только метки из второго (IR102) файла, а не файла (IR101). Я предполагаю, что второй код перезаписывается

Мне нужно сделать еще один новый хэш?

PS: С помощью этого можно получить среднее значение двух меток с помощью этого метода?

---Additional Код:

 //So this is the IRStudents file. This contains Student ID and Name.
 25987 Alan
 25954 Betty
 25654 Chris
 25622 David
 //So the StudentID has to match all the student Id with the mark files.

 //File 1 Mark 1 with marks in it. 
 25987 35.6
 25954 70.2
 25654 58.6
 25622 65.0

 //File 2 Mark 2 with marks in it. 
 25987 20.7
 25954 63.4
 25654 35.1
 25622 57.8

 //So the output file should be.

 25987 Alan
 Marks1: 35.6 Mark2: 20.7  AverageMark: (35.6+20.7)/2
 - - - - - - - -  - - -  - - - - - -  - - - - - - - - 
 25954 Betty
 Marks1: 70.2 Mark2: 63.4 AverageMark:(average)
 - - - - - -  - - -  - - - - - - - - - - - - - - - - 

Плюс к этому

  • 1
    Не могли бы вы показать пример входных файлов, и как вы хотите, чтобы выглядел вывод?
Теги:
file
hash

1 ответ

1
Лучший ответ

Прежде всего, вы снова открываете и записываете File_2.txt в File_2.txt дважды, а второй открытый File_2.txt первый. Вместо этого вы хотите хранить свои данные при чтении второго и третьего файлов, а затем выводятся в конце.

Один простой способ справиться с этим хранилищем - создать новый класс Student который будет состоять из идентификатора, имени и списка меток.

Обратите внимание, что если вы хотите вычислить среднее значение, то, вероятно, имеет смысл представлять метки, используя числовой тип типа double.

import java.util.*;
import java.io.*;

public class test1 {
    static class Student {
        String id;
        String name;
        List<Double> marks;

        public Student(String id, String name) {
            this.id = id;
            this.name = name;
            marks = new ArrayList<Double>();
        }
        public void addMark(Double d) {
            marks.add(d);
        }
        public void writeToPW(PrintWriter out) {
            out.println(id + " " + name);
            double d = 0;
            for (int i = 0; i < marks.size(); i++) {
                out.printf("Marks%d: %.2f ", (i+1), marks.get(i));
                d += marks.get(i);
            }
            out.println("AverageMark: " + d / marks.size());
            out.println("- - - - - -");    
        }
    }
    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, Student> students = new HashMap<String, Student>();

        // list to maintain the original order
        List<Student> orderedStudents = new ArrayList<Student>();


        //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(" ");
                Student student = new Student(arg[0], arg[1]);
                students.put(arg[0], student);
                orderedStudents.add(student);
            }
        }
        reader.close();


        reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("IR101.txt"))));
        while((line = reader.readLine()) != null){
            arg = line.split(" ");
            students.get(arg[0]).addMark(Double.parseDouble(arg[1]));
        }


        reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("IR102.txt"))));
        while((line = reader.readLine()) != null){
            arg = line.split(" ");
            students.get(arg[0]).addMark(Double.parseDouble(arg[1]));
        }

        // Now we can do writing.
        writer = new PrintWriter(new FileOutputStream(new File("File_2.txt")));
        for (Student s: orderedStudents) {
            s.writeToPW(writer);
        }
        writer.close();
    }
}
  • 0
    Большое спасибо за это. Аннотации действительно помогли мне понять код тоже.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню