PR2/Exercises/Testat1/Aufgabe2/Main.java

64 lines
1.9 KiB
Java

package Testat1.Aufgabe2;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<>();
try (LineNumberReader reader = new LineNumberReader(new FileReader("Exercises/Testat1/Aufgabe2/people"))){
String line;
boolean isOddLine = true;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
while((line = reader.readLine()) != null) {
if(isOddLine) {
String[] parts = line.split("\\s+");
LocalDate date = LocalDate.parse(parts[1], formatter);
String name = parts[2];
int age = Integer.parseInt(parts[3]);
double size = Double.parseDouble(parts[4].replace(',', '.'));
if(parts[0].equals("Person")) {
people.add(new Person(date, name, age, size));
}
else if(parts[0].equals("Student")) {
String subject = parts[5];
people.add(new Student(date, name, age, size, subject));
}
else if(parts[0].equals("Employee")) {
double salary = Double.parseDouble(parts[5]);
people.add(new Employee(date, name, age, size, salary));
}
else if(parts[0].equals("Teacher")) {
String field = parts[5];
people.add(new Teacher(date, name, age, size, field));
}
}
isOddLine = !isOddLine;
}
} catch (Exception e) {
e.printStackTrace();
}
for (Person person : people) {
System.out.println(person.toString());
}
System.out.printf("Durchschnittsalter: %s\n", Main.durchschnittRechner(people));
}
public static double durchschnittRechner (ArrayList<Person> people) {
if(people.isEmpty() || people == null) {
return 0.0;
}
int summe = 0;
for (Person person : people) {
summe = summe + person.getAge();
}
return (double) summe/people.size();
}
}