陈正磊


私信TA

用户名:RossTran

访问量:13632

签 名:

晨兴理荒秽,带月荷锄归。

等  级
排  名 178
经  验 6678
参赛次数 15
文章发表 34
年  龄 0
在职情况 学生
学  校 湖北生物科技职业学院
专  业

  自我简介:

解题思路:
方法一:创建学生类,然后冒泡排序

方法二:实现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 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区