原题链接:成绩排序
解题思路:
方法一:创建学生类,然后冒泡排序
方法二:实现Arrays.Sort的Comparator排序方法
注意事项:
参考代码:
方法一
import java.util.Scanner;
public class 成绩排序 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while (sc.hasNext()) {
int n=sc.nextInt();
Student stu[]=new Student[n];
for (int i = 0; i < n; i++) {
String name=sc.next();
int age=sc.nextInt();
int score=sc.nextInt();
stu[i]=new Student(name, age, score);
}
//冒泡排序
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;
}else
if(stu[j].Name.compareTo(stu[j+1].Name)==0){
if (stu[j].Age>stu[j+1].Age) {
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].Age+" "+stu[i].Score);
}
}
}
//学生类
public static class Student{
String Name;
int Age;
int Score;
public Student (String name,int age,int score) {
this.Name=name;
this.Age=age;
this.Score=score;
}
public Student () {
}
}
}方法二
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class 成绩排序2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
while (sc.hasNext()) {
int n=sc.nextInt();
sc.nextLine();
Student stu[]=new Student[n];
for (int i = 0; i < n; i++) {
String name=sc.next();
int age=sc.nextInt();
int score=sc.nextInt();
stu[i]=new Student(name, age, score);
}
//排序
Arrays.sort(stu,new Comparator<Student>() {
public int compare(Student stu1,Student stu2){
if (stu1.Score>stu2.Score) {
return 1;
}else
if(stu1.Score==stu2.Score){
if (stu1.Name.compareTo(stu2.Name)>0) {
return 1;
}else
if (stu1.Name.compareTo(stu2.Name)==0) {
if (stu1.Age>stu2.Age) {
return 1;
}
}
}
return -1;
}
});
//输出
for(int i=0;i<n;i++){
System.out.println(stu[i].Name+" "+stu[i].Age+" "+stu[i].Score);
}
}
}
//学生类
public static class Student{
String Name;
int Age;
int Score;
public Student (String name,int age,int score) {
this.Name=name;
this.Age=age;
this.Score=score;
}
}
}0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复