用java实现输入学生的。学号姓名性别年龄,放入一个数组中,并可分别调研用
时间: 2023-05-29 08:05:02 浏览: 352
以下是一个简单的Java程序,可以实现输入学生信息,并将其存储在一个数组中。程序允许用户选择不同的操作,如按学号、姓名、性别或年龄排序,或显示所有学生信息。
```
import java.util.*;
class Student {
String id;
String name;
String gender;
int age;
public Student(String id, String name, String gender, int age) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
}
public String toString() {
return id + "\t" + name + "\t" + gender + "\t" + age;
}
}
public class StudentArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = 0;
System.out.print("请输入学生人数:");
n = scanner.nextInt();
Student[] students = new Student[n];
for (int i = 0; i < n; i++) {
System.out.print("请输入第" + (i + 1) + "个学生的信息(学号 姓名 性别 年龄):");
String id = scanner.next();
String name = scanner.next();
String gender = scanner.next();
int age = scanner.nextInt();
students[i] = new Student(id, name, gender, age);
}
while (true) {
System.out.println("请选择操作:");
System.out.println("1. 按学号排序");
System.out.println("2. 按姓名排序");
System.out.println("3. 按性别排序");
System.out.println("4. 按年龄排序");
System.out.println("5. 显示所有学生信息");
System.out.println("6. 退出");
int choice = scanner.nextInt();
switch (choice) {
case 1:
Arrays.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.id.compareTo(s2.id);
}
});
break;
case 2:
Arrays.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name);
}
});
break;
case 3:
Arrays.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.gender.compareTo(s2.gender);
}
});
break;
case 4:
Arrays.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.age - s2.age;
}
});
break;
case 5:
System.out.println("学号\t姓名\t性别\t年龄");
for (Student s : students) {
System.out.println(s);
}
break;
case 6:
System.exit(0);
default:
System.out.println("无效操作,请重新选择。");
}
}
}
}
```
阅读全文