package pl.am.errors.lesson10;
import java.io.IOException;
public class FileFormatException extends IOException {
public FileFormatException() {
}
public FileFormatException(String s) {
super(s);
}
}
package pl.am.errors.lesson10;
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: " + e.getMessage());
} catch (FileFormatException e) {
System.err.println("Niepoprawny format pliku: " + e.getMessage());
} catch (Exception e) {
System.err.println("Inny błąd przy odczytywaniu z pliku: " + e.getMessage());
}
}
}
package pl.am.errors.lesson10;
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) throws FileFormatException {
String[] columns = fileLine.split(" ");
if (columns.length != 3) {
throw new FileFormatException("błędna ilość kolumn");
}
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 +
'}';
}
}