Сортировка обьектов при считывании из файла - Java
Всем привет,у меня есть файл в который я записываю обьекты, а потом их считываю. И сейчас я хочу их считывать с сортировкой, но что бы записаны были как я записал, а уже считывать с сортировкой. И так, у меня каждый обьект имеет имя, фимилию и пять оценок с предметов, так вот я хочу считьвать их на основе среднией из оценок по возростанию. Вот мой код что я имею на данный момент:
package com.company;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String imie = "", nazwisko = "";
double al = 0.0, po = 0.0, ptw = 0.0, ja = 0.0, wf = 0.0;
System.out.print("Ile studentow chcesz dodac: ");
int counter = scanner.nextInt();
String[] daneImieNazwisko = new String[counter * 2];
int imieCounter = 0, nazwiskoCounter = 1;
double[] daneOceny = new double[counter * 5];
int ocena01Counter = 0, ocena02Counter = 1, ocena03Counter = 2, ocena04Counter = 3, ocena05Counter = 4;
for (int i = 0; i < counter; i++) {
System.out.print("Podaj imie i nazwisko studenta" + (i + 1) + "\n");
scanner.nextLine();
System.out.print("imie: ");
imie = scanner.nextLine();
System.out.print("nazwisko: ");
nazwisko = scanner.nextLine();
System.out.print("Podaj ocene z przedmiotow\n");
System.out.print("algebra liniowa: ");
al = scanner.nextDouble();
System.out.print("programowanie obiektowe: ");
po = scanner.nextDouble();
System.out.print("podstawy technologii www: ");
ptw = scanner.nextDouble();
System.out.print("jezyk angielski: ");
ja = scanner.nextDouble();
System.out.print("wychowanie fizyczne: ");
wf = scanner.nextDouble();
daneImieNazwisko[imieCounter] = imie;
imieCounter = imieCounter + 2;
daneImieNazwisko[nazwiskoCounter] = nazwisko;
nazwiskoCounter = nazwiskoCounter + 2;
daneOceny[ocena01Counter] = al;
ocena01Counter = ocena01Counter + 5;
daneOceny[ocena02Counter] = po;
ocena02Counter = ocena02Counter + 5;
daneOceny[ocena03Counter] = ptw;
ocena03Counter = ocena03Counter + 5;
daneOceny[ocena04Counter] = ja;
ocena04Counter = ocena04Counter + 5;
daneOceny[ocena05Counter] = wf;
ocena05Counter = ocena05Counter + 5;
}
// for (int i = 0; i < daneImieNazwisko.length; i++) {
// System.out.print(daneImieNazwisko[i] + " ");
// }
// System.out.print("\n");
// for (int i = 0; i < daneOceny.length; i++) {
// System.out.print(daneOceny[i] + " ");
// }
System.out.print("\n");
Student student01 = new Student(daneImieNazwisko[0], daneImieNazwisko[1], daneOceny[0], daneOceny[1], daneOceny[2], daneOceny[3], daneOceny[4]);
System.out.print("\nDane studenta1: \n");
System.out.print(student01.showImieNazwisko() + "\n");
System.out.print(student01.showOceny());
System.out.print("\n");
Student student02 = new Student(daneImieNazwisko[2], daneImieNazwisko[3], daneOceny[5], daneOceny[6], daneOceny[7], daneOceny[8], daneOceny[9]);
System.out.print("\nDane studenta2: \n");
System.out.print(student02.showImieNazwisko() + "\n");
System.out.print(student02.showOceny());
System.out.print("\n");
Student student03 = new Student(daneImieNazwisko[4], daneImieNazwisko[5], daneOceny[10], daneOceny[11], daneOceny[12], daneOceny[13], daneOceny[14]);
System.out.print("\nDane studenta3: \n");
System.out.print(student03.showImieNazwisko() + "\n");
System.out.print(student03.showOceny());
System.out.print("\n");
ArrayList<Student> students = new ArrayList<>();
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("wynikiStudenci.ser"));
students.add(student01);
students.add(student02);
students.add(student03);
for (Student student : students) {
objectOutputStream.writeObject(student);
}
objectOutputStream.flush();
objectOutputStream.close();
System.out.print("Dane studentow zostaly zapisane do pliku \"wynikiStudenci.ser\"");
} catch (Exception exc) {
System.out.print("Blad: " + exc);
}
System.out.print("\n");
students.removeAll(students);
try {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("wynikiStudenci.ser"));
while (true) {
try {
students.add((Student) objectInputStream.readObject());
// Student obj = (Student) objectInputStream.readObject();
} catch (EOFException exc) {
break;
}
}
objectInputStream.close();
for (Student student : students) {
System.out.print("\n" + student.showImieNazwisko() + "\n" + student.showOceny());
}
} catch (Exception exc) {
System.out.print("Blad: " + exc);
}
}
}
package com.company;
import java.io.Serializable;
public class Student implements Serializable {
private String imie;
private String nazwisko;
private Indeks indeks;
private String test;
@Override
public String toString() {
return test;
}
public Student(String imie, String nazwisko, double ocena01, double ocena02, double ocena03, double ocena04, double ocena05) {
this.imie = imie;
this.nazwisko = nazwisko;
this.indeks = new Indeks(ocena01, ocena02, ocena03, ocena04, ocena05);
}
public String getImie() {
return imie;
}
public String getNazwisko() {
return nazwisko;
}
public String showImieNazwisko() {
String s = "Imie: " + getImie() + "\n" + "Nazwisko: " + getNazwisko();
return s;
}
public String showOceny() {
String p01 = indeks.getPrzedmiot01() + " / " + indeks.getOcena01();
String p02 = indeks.getPrzedmiot02() + " / " + indeks.getOcena02();
String p03 = indeks.getPrzedmiot03() + " / " + indeks.getOcena03();
String p04 = indeks.getPrzedmiot04() + " / " + indeks.getOcena04();
String p05 = indeks.getPrzedmiot05() + " / " + indeks.getOcena05();
return p01 + "\n" + p02 + "\n" + p03 + "\n" + p04 + "\n" + p05;
}
}
package com.company;
import java.io.Serializable;
public class Indeks implements Serializable {
private String przedmiot01 = "Algebra liniowa";
private String przedmiot02 = "Programowanie obiektowe";
private String przedmiot03 = "Podstawy technologii WWW";
private String przedmiot04 = "Jezyk angielski";
private String przedmiot05 = "Wychowanie fizyczne";
private double ocena01 = 4.0;
private double ocena02 = 4.0;
private double ocena03 = 4.0;
private double ocena04 = 4.0;
private double ocena05 = 4.0;
public Indeks(double ocena01, double ocena02, double ocena03, double ocena04, double ocena05) {
this.ocena01 = ocena01;
this.ocena02 = ocena02;
this.ocena03 = ocena03;
this.ocena04 = ocena04;
this.ocena05 = ocena05;
}
public String getPrzedmiot01() {
return przedmiot01;
}
public String getPrzedmiot02() {
return przedmiot02;
}
public String getPrzedmiot03() {
return przedmiot03;
}
public String getPrzedmiot04() {
return przedmiot04;
}
public String getPrzedmiot05() {
return przedmiot05;
}
public double getOcena01() {
return ocena01;
}
public double getOcena02() {
return ocena02;
}
public double getOcena03() {
return ocena03;
}
public double getOcena04() {
return ocena04;
}
public double getOcena05() {
return ocena05;
}
}
Ответы (1 шт):
Вам верно указали в комментариях, что для данной задачи нужно отсортировать список перед выводом, а откуда вы читаете объекты - не важно.
Как вариант:
Имплементируйте интерфейc Comparable<T> в классе Student так:
public class Student implements Serializable, Comparable<Student> {...}
Переопределите метод compareTo(T o) например так (это пример только для демонстрации логики compareTo(T o) для вашей задачи):
@Override
public int compareTo(Student o) {
int result = 0;
double avgThis = (indeks.getOcena01()
+ indeks.getOcena02()
+ indeks.getOcena03()
+ indeks.getOcena04()
+ indeks.getOcena05()) / 5;
double avgThat = (o.indeks.getOcena01()
+ o.indeks.getOcena02()
+ o.indeks.getOcena03()
+ o.indeks.getOcena04()
+ o.indeks.getOcena05()) / 5;
if (avgThis > avgThat) {
result = 1;
} else if (avgThis < avgThat) {
result = -1;
}
return result;
}
Отсортируйте список students перед выводом на консоль (или перед записью в файл) так:
Collections.sort(students);
Данный пример простой и показывает, как достигается возможность сортировать объекты, но в вашей задаче правильнее использовать компараторы.