题目描述
给出班里某门课程的成绩单,请你按成绩从高到低对成绩单排序输出,如果有相同分数则名字字典序小的在前。
输入格式
第一行为n (0 < n < 20),表示班里的学生数目;
接下来的n行,每行为每个学生的名字和他的成绩, 中间用单个空格隔开。名字只包含字母且长度不超过20,成绩为一个不大于100的非负整数。
输出格式
把成绩单按分数从高到低的顺序进行排序并输出,每行包含名字和分数两项,之间有一个空格。
样例输入
4
Kitty 80
Hanmeimei 90
Joey 92
Tim 28
样例输出
Joey 92
Hanmeimei 90
Kitty 80
Tim 28
思路
1.定义一个student结构体
2.排序(根据成绩
3.特殊情况(分数相同时根据名字字典序进行排序,利用compareto方法)
代码实现
import java.util.Scanner; public class Chengjifenxi { public static class student { String name=""; int score=0; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); student stu[]=new student[n]; for (int i = 0; i < n; i++) { stu[i]=new student(); stu[i].name=sc.next(); stu[i].score=sc.nextInt(); } for (int i = 0; i < n; i++) { for (int j = 0; j < n-i-1; j++) { if(stu[j].score<stu[j+1].score){ student temp=stu[j]; stu[j]=stu[j+1]; stu[j+1]=temp; }else if(stu[j].score==stu[j+1].score) { if(stu[j].name.compareTo(stu[j+1].name)>0){ student temp=stu[j]; stu[j]=stu[j+1]; stu[j+1]=temp; } } } } for (int i = 0; i < n; i++) { System.out.println(stu[i].name+" "+stu[i].score); } } }
|
结果实例

java中string类的常用方法
http://t.csdn.cn/L8jOo(作者:北风)