gpt4 book ai didi

java - Java 需要学生成绩排序帮助

转载 作者:行者123 更新时间:2023-12-02 06:58:01 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

您可以将相关字段封装到一个类中,例如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接口(interface)为算法提供了足够的信息来对实现所述接口(interface)的此类对象的集合进行排序。

关于java - Java 需要学生成绩排序帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17054451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com