- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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
可以封装字段 name
和 score
。
现在,您可以根据第二个字段 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/
我正在尝试在 JavaScript 中创建一个正则表达式搜索,它会接受以下等级中的一个:A、B+、B、C+、C、D、F、AF 或 WF。 我有以下正则表达式:^A-?|[BCD][+-]?|[AW]?
已关闭。此问题旨在寻求有关书籍、工具、软件库等的建议。它不符合 Stack Overflow guidelines 。它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题
我正在制作一个学生数据库,其中包含类(class) ID、类(class)名称、每门类(class)的学分、通过/失败声明和成绩。我的目标是让按钮显示总和(成绩)/总和(学分) 这是我编写的代码,它给
我正在努力弄清楚如何实现这个计数。模型是用户、测试、等级 用户 has_many 测试,测试 has_many 成绩。 每个等级都有一个计算分数(strong_pass、pass、fail、stron
我是一名优秀的程序员,十分优秀!