用400行代码写一个面向对象程序设计
时间: 2024-01-01 15:04:37 浏览: 57
面向对象程序设计代码
5星 · 资源好评率100%
以下是一个简单的面向对象程序设计的Java代码示例,该示例展示如何设计一个简单的学生管理系统。
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class StudentManagementSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Student> students = new ArrayList<>();
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:
Student student = new Student();
System.out.print("请输入学生姓名:");
student.setName(scanner.next());
System.out.print("请输入学生学号:");
student.setStudentId(scanner.next());
System.out.print("请输入学生年龄:");
student.setAge(scanner.nextInt());
students.add(student);
System.out.println("添加学生成功!");
break;
case 2:
System.out.print("请输入要查找的学生学号:");
String studentId = scanner.next();
for (Student s : students) {
if (s.getStudentId().equals(studentId)) {
System.out.println(s);
break;
}
}
break;
case 3:
System.out.print("请输入要删除的学生学号:");
studentId = scanner.next();
boolean found = false;
for (Student s : students) {
if (s.getStudentId().equals(studentId)) {
students.remove(s);
found = true;
System.out.println("删除学生成功!");
break;
}
}
if (!found) {
System.out.println("未找到该学生!");
}
break;
case 4:
System.out.print("请输入要修改的学生学号:");
studentId = scanner.next();
found = false;
for (Student s : students) {
if (s.getStudentId().equals(studentId)) {
System.out.print("请输入学生姓名:");
s.setName(scanner.next());
System.out.print("请输入学生年龄:");
s.setAge(scanner.nextInt());
found = true;
System.out.println("修改学生信息成功!");
break;
}
}
if (!found) {
System.out.println("未找到该学生!");
}
break;
case 5:
System.out.println("所有学生信息如下:");
for (Student s : students) {
System.out.println(s);
}
break;
case 6:
System.out.println("退出系统成功!");
System.exit(0);
break;
default:
System.out.println("输入错误,请重新输入!");
break;
}
}
}
}
class Student {
private String name;
private String studentId;
private int age;
public Student() {
}
public Student(String name, String studentId, int age) {
this.name = name;
this.studentId = studentId;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", studentId='" + studentId + '\'' +
", age=" + age +
'}';
}
}
```
在上面的示例中,我们设计了一个简单的学生管理系统。我们定义了一个Student类,用于存储学生的姓名、学号和年龄。我们还定义了一个StudentManagementSystem类,用于实现各种操作,如添加学生、查找学生、删除学生、修改学生信息和显示所有学生。
该程序使用面向对象的思想,将学生的信息封装在Student类中,并通过StudentManagementSystem类来实现对学生信息的管理。该程序还使用了集合类ArrayList来存储学生对象,使得程序的扩展性更好。
阅读全文