学生对Java所需的排序帮助进行评分

时间:2013-06-11 21:50:10

标签: java arrays sorting

import java.util.Scanner;
import java.util.Arrays;

class StudentScores {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the # of students");
    int numOfStudents = input.nextInt();
    int[] scores = new int[numOfStudents];
    String[] names = new String[numOfStudents];

    for (int i = 0; i < numOfStudents; i++) {
        input.nextLine();
        System.out.print("Enter name: ");
        names[i] = input.nextLine();
        System.out.print("Enter score: ");
        scores[i] = input.nextInt();
    }

                    // This doesn't sort anything, it just prints out the result in unsorted way
    /*for (int i = 0; i < numOfStudents; i++) {
        System.out.println(names[i] + " " + scores[i]);
    }*/

    Arrays.sort(scores);
    reverse(scores);


    for (int u: scores) {
        System.out.println(u);
    }
}

   public static int[] reverse(int[] array) {
    for (int i = 0, j = array.length - 1; i < j; i++, j--) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    return array;
  }
 }

最初的问题是: 编写一个程序,提示用户输入学生人数,学生姓名和分数,并按照分数的降序打印学生姓名。

我的问题是 如何使用排序的分数列表显示名称?

你一定不必给我一个完整的解决方案,只需给我一个提示,这样我就可以自己解决。

2 个答案:

答案 0 :(得分:2)

您可以将相关字段封装到一个类中,例如StudentRecord可以封装字段namescore

现在,您可以根据第二个字段score对这些对象的集合进行排序。当打印排序结果时,您将遍历集合并打印第一个字段name

举例说明:

public class StudentRecord implements Comparable<StudentRecord> {

    private String name;
    private int score;

    public StudentRecord(String name, int score) {
        this.name = name;
        this.score = score;
    }

    @Override
    public int compareTo(StudentRecord other) {
        if (score == other.score) return 0;
        else if (score < other.score) return -1;
        else return 1;
    }

    @Override
    public String toString() {
        return name;
    }


    public static void main(String[] args) {

        StudentRecord stu1 = new StudentRecord("Matt", 50);
        StudentRecord stu2 = new StudentRecord("John", 90);

        if (stu1.compareTo(stu2) == 0) {
            System.out.println(stu1.toString() + " has the same score with " + stu2.toString());
        }
        else if (stu1.compareTo(stu2) < 0) {
            System.out.println(stu1.toString() + " has a lower score than " + stu2.toString());
        }
        else {
            System.out.println(stu1.toString() + " has a higher score than " + stu2.toString());
        }

        // output:
        // Matt has a lower score than John

    }

}

在许多排序算法中,实现Comparable接口为算法提供了足够的信息来对实现所述接口的此类对象的集合进行排序。

答案 1 :(得分:0)

您无法使用Arrays.sort()来解决此问题,因为您需要将两个阵列排在一起。编写一个排序函数,按顺序对分数进行排序,每次交换两个分数时,也将学生与这些分数交换。