使用compareTo方法和数组按名称和测试分数对学生进行排序

时间:2012-11-10 23:09:41

标签: java arrays sorting interface compareto

我需要使用类似的interfact和compareTo方法按字母顺序排列学生列表,然后按测试分数排序。我正努力让这个在我的应用程序中工作。

需要从文本文件中读取名称列表。我不知道我的教授使用的文本文件中有多少名称,除了它将小于100.我还应该在底部显示成绩的平均值,并在任何旁边写一条消息比平均水平低15分的学生。我还没有真正了解写作消息部分,因为我目前仍然坚持要打印和排序的名称和分数。

文本文件应如下所示:

  

Steelman Andrea 95

     

Murach Joel 98

     

Lowe Doug 82

     

Murach Mike 93

这就是我到目前为止......如果有人能给我一点方向,我会很感激。谢谢。

package chapt11;
import java.io.FileReader;  
import java.util.Arrays; 
importjava.util.Scanner;
public class CH11AS8App {

/**
 * @param args
 */
public static void main(String[] args) throws Exception {

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

    Scanner aScanner = new Scanner(new FileReader(
            "src//chapt11//ch11AS8data.txt"));

    Student [] studentArray;

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

    int nStudent = 100;  //array size not set unit run time
    studentArray = new Student[nStudent];

    for (int i=0; i<nStudent; i++)
    {
    System.out.println();

        while (aScanner.hasNext()) {
            lastName = aScanner.next();
            firstName = aScanner.next();
            examScore = aScanner.nextInt();

            System.out.println("Student " + nStudent++ + " " + firstName
                    + " " + lastName + " " + +examScore);

            studentArray[i] = new Student(lastName, firstName, examScore);


    }
        double sum = 0.0;
        sum += examScore;
        average = sum/nStudent;

        Arrays.sort(studentArray);

        System.out.println();

        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);

        }
}
}
public interface Comparable {
    int compareTo(Object o);
}

class Student implements Comparable {

    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(Object o) {
        Student s = (Student) o;

        if (s.lastName.equals(lastName)) {
            return firstName.compareToIgnoreCase(s.firstName);
        } else {
            return lastName.compareToIgnoreCase(s.lastName);
        }
    }

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

    }

}

}

4 个答案:

答案 0 :(得分:2)

首先,完全删除您的Comparable界面。使用JDK中的Comparable

将您的代码更改为此

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
    }
}

另请注意,在条件return之后没有“else”,所以我省略了代码的冗余部分

答案 1 :(得分:0)

  1. 您不得自行声明Comparable接口。只需使用它。
  2. 你必须在循环内对学生的考试成绩求和,但计算平均值,在循环外排序数组。

答案 2 :(得分:0)

您的代码中很少有需要更正的内容:

  1. 您的Student类是内部类,因此要创建该类的对象,您需要外部类的第一个对象。您可能希望嵌套类可以在没有外部对象的情况下创建对象(只需将static修饰符添加到Student类)
  2. 要使用Arrays.sort()对象排序数组,必须实现java.lang.Comparable接口,而不是您创建的接口。
  3. 您可以将遗传工具与Comparable<T>一起使用,因此请尝试以Student方式实施您的implements Comparable<Student>{课程,这样compareTo方法就可以了

    public int compareTo(Student s){//body 
    

    而不是:

    public int compareTo(Object o){ 
        Student s = (Student) o; 
    
  4. 由于您的数组将包含空值(未填充位置的默认值),因此您需要阻止排序比较器在null元素上调用compareTo。为此,请使用Arrays.sort(Object[] a, int fromIndex, int toIndex)版本的排序算法。

  5. 从文件中收集信息时再次检查您的逻辑。为了方便起见,不要一次做几件事。首先收集所有数据,然后进行统计。

  6. 每次向其添加新数据时都不要对数组进行排序,请在添加所有数据后进行排序。

答案 3 :(得分:0)

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;

        }

    }
}