Java、对学生排序
作者:互联网
编写一个程序,提示用户输入学生个数、学生姓名和他们的成绩,然后按照学生成绩的降序打印学生的姓名。
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;
}
}
}
}
标签:Java,String,int,System,学生,names,scores,排序,currentIndex 来源: https://blog.csdn.net/m0_62659797/article/details/122947973