package com.huaruiedu._05._09ArrayList;
import java.util.ArrayList;
import java.util.Scanner;
/*
1.定义一个学生集合,有年龄,考试分数,姓名三个属性
请从控制台接收5个学生,并根据三个属性进行排序
*/
public class Student {
private String name;
private int age;
private int score;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
Scanner input = new Scanner(System.in);
ArrayList
public void outMethod() {
System.out.println("请输入有几个学生:");
int num = input.nextInt();
for (int i = 0; i < num; i++) {
list.add(new Student());
System.out.println("请输入第" + (i + 1) + "个学生的姓名:");
list.get(i).setName(input.next());
System.out.println("请输入第" + (i + 1) + "个学生的年龄:");
list.get(i).setAge(input.nextInt());
System.out.println("请输入第" + (i + 1) + "个学生的分数:");
list.get(i).setScore(input.nextInt());
}
System.out.println("按姓名排序:(默认)");
// 调用打印方法
output();
System.out.println("按年龄排序:");
for (int i = 0; i < list.size() - 1; i++) {
for (int j = 0; j < list.size() - 1 - i; j++) {
if (list.get(j).getAge() < list.get(j + 1).getAge()) {
Student temp = list.get(j);
list.set(j, list.get(j + 1));
list.set(j + 1, temp);
}
}
}
// 调用打印方法
output();
System.out.println("按分数排序:");
for (int i = 0; i < list.size() - 1; i++) {
for (int j = 0; j < list.size() - 1 - i; j++) {
if (list.get(j).getScore() < list.get(j + 1).getScore()) {
Student temp = list.get(j);
list.set(j, list.get(j + 1));
list.set(j + 1, temp);
}
}
}
// 调用打印方法
output();
}
// 打印方法
public void output() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getName() + "\t"
+ list.get(i).getAge() + "\t" + list.get(i).getScore());
}
}
}
测试:
package com.huaruiedu._05._09ArrayList;
public class StudentTest2 {
public static void main(String[] args) {
Student stu = new Student();
stu.outMethod();
}
}