编写一个程序,提示用户输入学生个数、学生姓名和他们的成绩,然后按照学生成绩的降序打印学生的姓名。
package pack2;
import java.util.Scanner;
public class Sequence {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter the number of students: ");
int numbers = input.nextInt();
double[] scores = new double[numbers];
String[] names = new String[numbers];
for (int i = 0; i < names.length; i++) {
System.out.print("Enter grade and name of student "+(i + 1)+": ");
scores[i] = input.nextDouble();
names[i] = input.nextLine();
}
sort(scores, names);
System.out.println();
for (int i = 0; i < scores.length; i++)
System.out.println(names[i]+" "+scores[i]);
}
}
/**对学生排序*/
public static void sort(double[] scores, String[] names) {
for (int i = 0; i < scores.length - 1; i++) {
double currentMax = scores[i];
int currentIndex = i;
for (int j = i + 1; j < scores.length; j++)
if(currentMax < scores[j]) {
currentMax = scores[j];
currentIndex = j;
}
if(currentIndex != i) {
scores[currentIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentIndex];
names[currentIndex] = names[i];
names[i] = temp;
}
}
}
}