Using the compareTo method with an array to sort students by name and test score

你离开我真会死。 提交于 2019-12-04 19:02:58

Firstly, delete entirely your Comparable interface. Use Comparable from the JDK.

Change your code to this

public static class Student implements Comparable<Student> {

    // rest of class omitted

    @Override
    public int compareTo(Student s) {
        if (s.lastName.equals(lastName)) {
            return firstName.compareToIgnoreCase(s.firstName);
        }
        return lastName.compareToIgnoreCase(s.lastName);return
    }
}

Note also that there is no "else" after a conditional return, so I omitted that redundant part of the code

  1. You must not declare Comparable interface by yourself. Simply use it.
  2. You must sum exam scores of students inside loop but count average, sort array outside the loop.

There are few things that needs correction in your code:

  1. Your Student class is inner class so to create object of that class you need first object of outer class. You probably wanted nested class that objects can be created without outer object (just add static modifier to Student class)
  2. To sort array with Arrays.sort() object must implement java.lang.Comparable interface, not interface created by you.
  3. You can use generics with Comparable<T> so try implementing your Student class with implements Comparable<Student>{ this way your compareTo method will can like

    public int compareTo(Student s){//body 
    

    instead of:

    public int compareTo(Object o){ 
        Student s = (Student) o; 
    
  4. Since your array will contain nulls (its default value for not filled places) you need to prevent sorting comparator from invoking compareTo on null element. To do it use Arrays.sort(Object[] a, int fromIndex, int toIndex) version of sorting algorithm.

  5. Check again your logic while collecting informations from file. To make things easier don't do few things at once. First collect all data, then do statistics.

  6. Don't sort array every time you add new data to it, do it after you add all data.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CH11AS8App {

    public static void main(String[] args) throws Exception {

        System.out.println("Welcome to the Student Scores Application.");
        System.out.println();

        List<Student> studentArray = new ArrayList<Student>();

        String lastName;
        String firstName;
        int examScore = 0;
        double average = 0;

        String line;

        FileReader reader = new FileReader("src//chapt11//ch11AS8data.txt");
        BufferedReader bufferedReader = new BufferedReader(reader);
        String[] split;

        while ((line = bufferedReader.readLine()) != null) {
            split = line.split("\\s+");
            lastName = split[0];
            firstName = split[1];
            examScore = Integer.valueOf(split[2]);

            studentArray.add(new Student(firstName, lastName, examScore));
            double sum = 0.0;
        }
        Collections.sort(studentArray);

        System.out.println();

        System.out.println("sorted:" + studentArray);

        for (Student aStudent : studentArray) {
            System.out.println(aStudent);

            if (examScore <= (average - 10)) {
                System.out.println("Score 10 points under average");
            }
            System.out.println("Student Average:" + average);

        }
    }

    static class Student implements Comparable<Student> {

        private String firstName;
        private String lastName;
        private int examScore;

        public Student(String firstName, String lastName, int examScore) {
            this.firstName = firstName;
            this.examScore = examScore;
            this.lastName = lastName;
        }

        // Get & Set Methods
        public int getExamScore() {
            return examScore;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        @Override
        public int compareTo(Student s) {

            if (this.firstName.equalsIgnoreCase(s.firstName)) {
                if (this.lastName.equalsIgnoreCase(s.lastName)) {
                    return this.examScore - s.examScore;
                } else {
                    return this.lastName.compareTo(s.lastName);
                }
            } else {
                return this.firstName.compareTo(s.firstName);
            }


        }

        public String toString() {
            return lastName + ", " + firstName + ": " + examScore;

        }

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!