So I am working on writing code that will sort a list in various ways based on the Comaparable interface implemented by a class and also several Comparators. So I have a Student class and a Runner (for running the program). My issue is that I am importing data from the file, adding it to an arrayList, using a comparator to sort it, and then printing it out. When I do that I don't get the output that I should. When I print out the data write after importing it, it looks like:
Deirdre 70 62
Florence 37 90
Chris 60 68
Aaron 53 80
Elmer 91 40
Betty 79 50
^That is also what the txt file that I import looks like. And that is what the output needs to look similar to.
Instead the output looks like:
[Student@45ee12a7, Student@330bedb4, Student@2503dbd3, Student@4b67cf4d, Student@7ea987ac, Student@12a3a380]
This is the student class:
public class Student implements Comparable<Student> {
private String name;
private int score1, score2;
public Student (String name, int score1, int score2){
this.name = name;
this.score1 = score1;
this.score2 = score2; }
public String getName(){
return name; }
public int getScore1(){
return score1; }
public int getScore2(){
return score2; }
@Override
public int compareTo(Student o) {
return this.name.compareTo(o.name); } }
The Runner class is:
public class Runner {
public static void main(String[] args) {
File grades = new File("grades.txt");
try{
Scanner inScan = new Scanner(grades);
ArrayList<Student> list = new ArrayList();
while(inScan.hasNext()){
Student iS = new Student (inScan.next(), inScan.nextInt(), inScan.nextInt());
list.add(iS);
System.out.printf("%-10s %3d %3d\n", iS.getName(), iS.getScore1(), iS.getScore2()); }
System.out.println("=======================");
Collections.sort(list,new CompareScore1());
System.out.println(list);
System.out.println("=======================");
Collections.sort(list, new CompareScore2());
System.out.println(list);
System.out.println("=======================");
Collections.sort(list, new CompareSum());
System.out.println(list); }
catch(FileNotFoundException fnfe){
System.out.println("File not found: " + "grades.txt");
System.exit(1); } }
public static class CompareScore1 implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.getScore1() - o2.getScore1(); } }
public static class CompareScore2 implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.getScore2() - o2.getScore2(); } }
public static class CompareSum implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.getScore1() + o2.getScore2(); } }
Can you guys tell me what I am doing wrong? Thank you in advance