How to read a text file in Java and split it?

Basia :

I need help with writting a program, which will read me a file in Java and then split the words and will count the average of notes. So I have a file in Java called dziennik.txt and there in two lines I have a name, surname, the number of notes and then the notes of a student. It looks like this:

Mark Stank 3 4 5 6

Veronica Lee 2 2 4

So what I need to do is split words so that program will know that the 3 word is a number of notes and the next ones are these notes and it will count the average. For now I have sth like this:

import java.io.*;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.util.Scanner;

public class FileWrite {

    public static void main(String[] args) throws IOException {


        StringBuilder dziennik = new StringBuilder();

        try (BufferedReader br = Files.newBufferedReader(Paths.get("dziennik.txt"))) {

            // read line by line
            String line;
            while ((line = br.readLine()) != null) {
                dziennik.append(line).append("\n");
                String[] pair = line.split(" ");

            }

        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        }

        System.out.println(dziennik);
    }

}

I am new to this, so please explain this to me as simple as it can be .

Agile :

Similar to what spork mentioned. Here's a way to get the average number of notes per student:

StringBuilder dziennik = new StringBuilder();
double total = 0; // Added line
double counter = 0; // Added line
try (BufferedReader br = Files.newBufferedReader(Paths.get("dziennik.txt"))) {
    // read line by line
    String line;
    while ((line = br.readLine()) != null) {
        dziennik.append(line).append("\n");
        String[] pair = line.split(" ");
        total = total + Double.valueOf(pair[2]); // Added line
        counter++; // Added line
    }
    System.out.println("Average number of notes per student: " + total / counter); // Added line
} catch (IOException e) {
    System.err.format("IOException: %s%n", e);
}
System.out.println(dziennik);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=357605&siteId=1