1. 程式人生 > >JAVA實驗四:從鍵盤錄入若干個學生的姓名和分數

JAVA實驗四:從鍵盤錄入若干個學生的姓名和分數

題目

編寫一個程式,使用者可以從鍵盤錄入若干個學生的姓名和分數(程式每次提示使用者輸入“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()之間的區別

  • 淺談兩者之間的區別的時候,MapSetList 等集合中,他們都提共了一個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()方法忽略大小寫;