【问题标题】:Using the compareTo method with an array to sort students by name and test score使用带有数组的 compareTo 方法按姓名和考试成绩对学生进行排序
【发布时间】:2012-11-10 23:09:40
【问题描述】:

我需要使用可比较的 interfact 和 compareTo 方法来按字母顺序对学生列表进行排序,然后按考试成绩排序。我正在努力让它在我的应用程序中工作。

需要从文本文件中读取名称列表。我不知道我的教授使用的文本文件中有多少个名字,除了它会少于 100 个。我还应该在底部显示平均成绩,并在任何旁边写一条消息低于平均水平 15 分的学生。我还没有真正进入写作信息部分,因为我目前正忙于获取姓名和分数以进行打印和排序。

文本文件应如下所示:

钢铁侠安德里亚 95

穆拉赫乔尔 98

洛道格 82

穆拉赫迈克 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;
    
    }

}

}

【问题讨论】:

  • 您有具体问题吗?
  • 我无法让我的代码对列表进行排序...我想我不明白如何使用数组和 compareTo 方法,因为我编写的代码不起作用。跨度>

标签: java arrays sorting interface compareto


【解决方案1】:

首先,完全删除您的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”,所以我省略了代码的冗余部分

【讨论】:

  • 谢谢,我做出了更改,但仍在努力让列表在控制台中排序。有什么想法为什么它不起作用?
  • @newB 你怎么知道它没有排序?你得到什么输出? (并确认您输入的内容)。
  • 这就是我得到的输出... 欢迎来到学生分数应用程序。学生 1 Andrea Steelman 95 学生 2 Joel Murach 92 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 at chapt11.CH11AS8App.main(CH11AS8App.java:43) 我在应用程序中做错了,但和我一样多玩弄它我不知道是什么......
  • 在读取周围丢失 for 循环 - 这没有任何意义。另外,使用List,而不是数组。在现实世界中没有人使用数组。我认为这是一项任务——只有糟糕的老师才会让你使用数组。
  • 谢谢。不幸的是,它是用于赋值,使用数组是规范的一部分。
【解决方案2】:
  1. 不得自行声明 Comparable 接口。只需使用它。
  2. 您必须在循环内对学生的考试成绩求和,但计算平均值,在循环外对数组进行排序。

【讨论】:

  • 第一个推荐的意思是我应该省略吗?: public interface Comparable { int compareTo(Object o);感谢您的帮助。
【解决方案3】:

您的代码中有几处需要更正:

  1. 您的Student 类是内部类,因此要创建该类的对象,您需要外部类的第一个对象。您可能想要嵌套类,可以在没有外部对象的情况下创建对象(只需将 static 修饰符添加到 Student 类)
  2. 要使用Arrays.sort() 对象对数组进行排序,必须实现java.lang.Comparable 接口,而不是您创建的接口。
  3. 您可以将泛型与Comparable&lt;T&gt; 一起使用,因此请尝试使用implements Comparable&lt;Student&gt;{ 实现您的Student 类,这样您的compareTo 方法就会喜欢

    public int compareTo(Student s){//body 
    

    代替:

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

  5. 在从文件中收集信息时再次检查您的逻辑。为了让事情变得更容易,不要一次做几件事。首先收集所有数据,然后进行统计。

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

【讨论】:

  • 感谢您的帮助...我现在将着手解决这些问题。
  • 我已经能够纠正我犯的前几个错误,但是在第 4 个问题上遇到了困难。 fromIndex 会是 0,toIndex 会是 100 吗?
  • 计算您在数组中放置了多少学生。然后调用Arrays.sort(studentArray,0,studentCounter),因为这个排序方法的参数是:a要排序的数组,fromIndex要排序的第一个元素(包括)的索引,toIndex最后一个元素的索引(不包括)进行排序。
  • 我不知道文本文件中有多少学生,我的教授不会告诉我们,因为他说无论文本文件中有多少学生,它都应该工作(基本上,他可能使用几个文本文件,每个文件有不同数量的学生来测试我们)。如果我听起来像个白痴,我很抱歉,我对这一切都很陌生,似乎无法掌握数组。我确实认为我越来越接近并感谢您的时间和帮助。
  • @newB 在从文件中读取学生数据之前创建一些计数变量,例如int counter=0,然后在将每个学生放入数组后增加其值,例如ideone.com/mIhD53。现在我要睡觉了,所以几个小时都不会回答你的问题。祝你的代码好运。
【解决方案4】:
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;

        }

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多