用java写一个简单的学生系统
时间: 2023-04-10 14:03:10 浏览: 84
好的,以下是一个简单的学生系统的 Java 代码:
```
import java.util.ArrayList;
import java.util.Scanner;
public class StudentSystem {
private ArrayList<Student> students;
public StudentSystem() {
students = new ArrayList<>();
}
public void addStudent(Student student) {
students.add(student);
}
public void removeStudent(Student student) {
students.remove(student);
}
public void printAllStudents() {
for (Student student : students) {
System.out.println(student);
}
}
public static void main(String[] args) {
StudentSystem system = new StudentSystem();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请输入操作:1.添加学生 2.删除学生 3.查看所有学生 4.退出");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("请输入学生姓名:");
String name = scanner.next();
System.out.println("请输入学生年龄:");
int age = scanner.nextInt();
Student student = new Student(name, age);
system.addStudent(student);
System.out.println("添加成功!");
break;
case 2:
System.out.println("请输入要删除的学生姓名:");
String removeName = scanner.next();
boolean removed = false;
for (Student s : system.students) {
if (s.getName().equals(removeName)) {
system.removeStudent(s);
removed = true;
System.out.println("删除成功!");
break;
}
}
if (!removed) {
System.out.println("未找到该学生!");
}
break;
case 3:
system.printAllStudents();
break;
case 4:
System.out.println("退出系统!");
return;
default:
System.out.println("无效操作!");
break;
}
}
}
}
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "姓名:" + name + ",年龄:" + age;
}
}
```
阅读全文