ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java、对学生排序

2022-02-28 13:01:23  阅读:173  来源: 互联网

标签:Java String int System 学生 names scores 排序 currentIndex


        编写一个程序,提示用户输入学生个数、学生姓名和他们的成绩,然后按照学生成绩的降序打印学生的姓名。


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有