2 回答
TA贡献1830条经验 获得超9个赞
创建一个包装类(比如Student)来存储学生姓名和分数。然后使用比较器对它们进行排序以比较标记。
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class testing {
public static void main(String[] args) {
int n = 5;//total no of students
Scanner in = new Scanner(System.in);
System.out.println("Enter Students name:");
Student[] students = new Student[n];
for (int i = 0; i<n; i++)
{
students[i] = new Student();
students[i].name = in.nextLine();
}
System.out.println("Enter marks:");
for (int i = 0; i<n; i++)
{
students[i].mark = in.nextInt();
}
Arrays.sort(students, new MarkComparator());
for (int i = 0; i < n; i++)
{
System.out.println(students[i].name + " - "+ students[i].mark);
}
}
}
class Student {
int mark;
String name;
}
class MarkComparator implements Comparator {
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.mark>=s2.mark) {
return 1;
} else {
return -1;
}
}
}
示例输出:
Enter Students name:
alex
bertha
chris
dan
ervin
Enter marks:
50
40
30
20
10
ervin - 10
dan - 20
chris - 30
bertha - 40
alex - 50
TA贡献1815条经验 获得超10个赞
这应该适合你
// Class student
public class Student implements Comparable {
public String Name;
public double Mark;
// Should implement comparable to be able to compare it via Marks
@Override
public int compareTo(Student per) {
if(this.Mark == per.Mark)
return 0;
else
return this.Mark > per.Mark ? 1 : -1;
}
}
//total no of students
int n = 5;
// list of students and their marks
Student[] s = new Student[n];
// Scanner
Scanner in = new Scanner(System.in);
// Get student names and their marks
for (int i = 0; i<s.length; i++)
{
s[i] = new Student();
System.out.println("Enter Student #" + i + " name :");
s[i].Name = in.nextLine();
System.out.println("Enter Student #" + i + " mark :");
s[i].mark = in.nextDouble();
}
Arrays.sort(s);
for (int i = 0; i < s.length; i++)
{
System.out.println(s[i].Name + " : " + s[i].Mark);
}
添加回答
举报