try z zasobami

package pl.am.errors.lesson9;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {
    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(new File("lista.txt"))) {

            float sum = 0;
            int number = 0;

            while (scanner.hasNext()) {
                number++;
                Student student = Student.fromFileLine(scanner.nextLine());
                sum += student.getSchoolGrade();
                System.out.println(student);
            }

            System.out.println("średnia z matematyki: " + sum/ number);
        } catch (FileNotFoundException e) {
            System.err.println("Plik o podanej nazwie nie istnieje");
        } catch (Exception e) {
            System.err.println("Inny błąd przy odczytywaniu z pliku");
        }

    }
}
package pl.am.errors.lesson9;

public class Student {
    private String firstName;
    private String surname;
    private int schoolGrade;

    public Student(String firstName, String surname, int schoolGrade) {
        this.firstName = firstName;
        this.surname = surname;
        this.schoolGrade = schoolGrade;
    }

    public static Student fromFileLine(String fileLine) {
        String[] columns = fileLine.split(" ");
        String firstName = columns[0];
        String surname = columns[1];
        int schoolGrade = Integer.parseInt(columns[2]);

        return new Student(firstName, surname, schoolGrade);
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public int getSchoolGrade() {
        return schoolGrade;
    }

    public void setSchoolGrade(int schoolGrade) {
        this.schoolGrade = schoolGrade;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Override
    public String toString() {
        return "Student{" +
                "firstName='" + firstName + '\'' +
                ", surname='" + surname + '\'' +
                ", schoolGrade=" + schoolGrade +
                '}';
    }
}

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *