版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fighting123678/article/details/83902743
题目
编写一个程序,用户可以从键盘录入若干个学生的姓名和分数(程序每次提示用户输入“Y”或“N”决定是否继续录入学生信息,如果用户输入“N”则用户输入完毕。输入的“Y”、“N”不区分大小写)。用户录入完毕后,程序按成绩由高到低的顺序输出学生的姓名和分数(姓名和分数之间用一个空格分割)。【说明:键盘输入可以使用Scanner类】
答案
import java.util.*;
public class Main
{
public static void find()
{
ArrayList<Student> a=new ArrayList<Student>();//每个元素都是Student类型的;
Scanner scan=new Scanner(System.in);
while(true)
{
Student s=new Student();
System.out.print("Please input the studnet`s name:");
s.name=scan.next();
System.out.print("Please input the studnet`s score:");
s.score=scan.nextDouble();
a.add(s);
System.out.print("Please input Y or N");
String b=scan.nextLine();
String ss=scan.next();
if(ss.compareToIgnoreCase("n")==0||ss.compareToIgnoreCase("y")!=0)//忽略大小写,同时只能是Y或者y或者N或者n
{
break;
}
}
Collections.sort(a, new ScoreCompare());//不能是Array.sort()//两种写的方式;
//a.sort(new ScoreCompare());//不能是Array.sort()
Iterator it=a.iterator();
for(int i=0;it.hasNext();i++)
{
System.out.println(it.next());
}
}
public static void main(String[] args)
{
find();
}
}
class Student
{
protected String name;
protected double score;
public String toString()
{
return name+" "+score;
}
}
class ScoreCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.score>s2.score) return -1;
else if(s2.score<s2.score) return 1;
else return 0;
}
}
解析
1、Collections.sort()和Array.sort()之间的区别
- 浅谈两者之间的区别的时候,
Map
,Set
,List
等集合中,他们都提共了一个Collections.sort()排序方法
https://blog.csdn.net/fighting123678/article/details/83662308
- 不同类型的数组中,会提供Array.sort()排序方法;
但是,实际上,并非这样浅显的区别,详细分析见此博客https://blog.csdn.net/TimHeath/article/details/68930482
2、注意这个题目中的Comparator排序方法的两种写法
https://blog.csdn.net/qq_23179075/article/details/78753136
思路
1、虽然在JAVA中无法使用结构体,但是,可以使ArrayList容器中的每个元素都是Student类型的;
2、注意输入的只能是Y或者y或者N或者n,同时,可以使用compareToIgnoreCase()方法忽略大小写;