Search code examples
javareadfile

Displaying a text file in Java


I am a beginner in Java programming.

I have a text file, for example C:/Temp/dat.txt.

This is the code I have set in the Main Class:

public static boolean readFile(String filename) {
    File file = new File(filename);

    try {
        Scanner scanner = new Scanner(file);
        while(scanner.hasNextLine()){
            String[] words = scanner.nextLine().split(",");

            int id = Integer.parseInt(words[0]);
            String firstName = words[1];
            String lastName = words[2];
            int mathMark1 = Integer.parseInt(words[3]);
            int mathMark2 = Integer.parseInt(words[4]);
            int mathMark3 = Integer.parseInt(words[5]);
            int englishMark1 = Integer.parseInt(words[6]);
            int englishMark2 = Integer.parseInt(words[7]);
            int englishMark3 = Integer.parseInt(words[8]);

            addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,englishMark1,englishMark2,englishMark3); 
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        System.out.println("Failed to read file");
    }
    return true;
}

I now need to display this data from the text file under the following method:

private static void displayReportByMarks() {

}

How do I get the report to display from the text file within this method, and what is the appropriate code to put(if any) in the Main method of this class.

I hope this makes sense, as I said I am a complete novice at Java and can't get my head around this.

Many thanks

Amanda


Solution

  • Supposing you have a Stundent implemented as a staandard POJO, first implement the addStudent method:

    private List<Student> students = new ArrayList<>();
    
    private static void addStudent(int id, String firstName, String lastName, 
                                   int mathMark1, int mathMark2, int mathMark3, 
                                   int englishMark1, int englishMark2,
                                   int englishMark3) {
        students.add(new Student(id, firstName, lastName, mathMark1, mathMark2,
                         mathMark3, englishMark1, englishMark2,englishMark3));
    }
    

    Then, you can implement the printing method:

    private static void displayReportByMarks() {
         List<Student> studentsByMarks = students.stream().sorted(
                 (s1, s2) -> //just do the comparison for sorting here
                 )).collect(Collectors.toList());
         for (Student : students) {
              // assuming you have a Student.toString() method implemeted.
              System.out.println(student);
         }
    }