Java、对学生排序

2022/2/28 14:21:32

本文主要是介绍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、对学生排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程