1. 程式人生 > >山科java作業 2-2 118

山科java作業 2-2 118

118 - 學生類

Time Limit: 1000   Memory Limit: 65535
Submit: 728  Solved: 363

Description

有一個學生類的結構如下:
class Student {
	private int no;
	private String name;
        private int score;
	
	public Student(int _no, String _name, int _score) {
		no = _no;
		name = _name;
                score = _score;
	}
        public int getNo() {return no;}
        public String getName() {return name;}
        public int getScore() {return score;}
	
	public void print(){
		System.out.println(no + " "+name+" "+score);
	}
}

請構造main函式完成如下功能:
從鍵盤中讀入三個學生的資訊,比較他們的成績,按照成績由高到低排列輸出

Input

三個學生的學號、姓名、成績

Output

由高到低排列輸出的三個學生資訊

Sample Input

1 wang 89
2 liu 78
3 ma 90

Sample Output

3 ma 90
1 wang 89
2 liu 78

Post Append Code
class Student {
	private int no;
	private String name;
        private int score;
	
	public Student(int _no, String _name, int _score) {
		no = _no;
		name = _name;
                score = _score;
	}
        public int getNo() {return no;}
        public String getName() {return name;}
        public int getScore() {return score;}
	
	public void print(){
		System.out.println(no + " "+name+" "+score);
	}
}

答案:

package 學生類;
import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		Student []stu = new Student[3];
		int n,s;
		String name;
		int i,j;
		for(i = 0; i < 3;i++)
		{
			n = scanner.nextInt();
			name =  scanner.next();
			s = scanner.nextInt();
			stu[i] = new Student(n,name,s);
		}
		for(i = 0;i < 2;i++)
		{
			for(j = i + 1; j < 3;j++)
			{
				Student tmp;
				if(stu[i].getScore() < stu[j].getScore())
				{
					tmp = stu[i];
					stu[i] = stu[j];
					stu[j] = tmp;
				}
			}
		}
		for(i = 0;i < 3;i++)
		{
			stu[i].print();
		}
		scanner.close();
		

	}

}

class Student {
	private int no;
	private String name;
        private int score;
	
	public Student(int _no, String _name, int _score) {
		no = _no;
		name = _name;
                score = _score;
	}
        public int getNo() {return no;}
        public String getName() {return name;}
        public int getScore() {return score;}
	
	public void print(){
		System.out.println(no + " "+name+" "+score);
	}

}