以下是一个简单的Java选课系统的源代码,包括小标题和单元表格:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; class Course { private String courseName; private int courseId; public Course(String courseName, int courseId) { this.courseName = courseName; this.courseId = courseId; } public String getCourseName() { return courseName; } public int getCourseId() { return courseId; } } class Student { private String studentName; private int studentId; private List<Course> courses; public Student(String studentName, int studentId) { this.studentName = studentName; this.studentId = studentId; this.courses = new ArrayList<>(); } public void addCourse(Course course) { courses.add(course); } public void removeCourse(Course course) { courses.remove(course); } public void displayCourses() { System.out.println("学生 " + studentName + " 的课程:"); for (Course course : courses) { System.out.println("课程ID:" + course.getCourseId() + ",课程名称:" + course.getCourseName()); } } } public class CourseSelectionSystem { public static void main(String[] args) { List<Course> courses = new ArrayList<>(); courses.add(new Course("计算机科学", 1)); courses.add(new Course("数学", 2)); courses.add(new Course("物理", 3)); courses.add(new Course("化学", 4)); Student student = new Student("张三", 1001); Scanner scanner = new Scanner(System.in); while (true) { System.out.println("请选择操作:1. 选课 2. 退课 3. 查看已选课程 4. 退出"); int operation = scanner.nextInt(); if (operation == 1) { System.out.println("请输入要选的课程ID:"); int courseId = scanner.nextInt(); Course selectedCourse = null; for (Course course : courses) { if (course.getCourseId() == courseId) { selectedCourse = course; break; } } if (selectedCourse != null) { student.addCourse(selectedCourse); System.out.println("选课成功!"); } else { System.out.println("课程不存在,请重新选择!"); } } else if (operation == 2) { System.out.println("请输入要退的课程ID:"); int courseId = scanner.nextInt(); Course removedCourse = null; for (Course course : student.courses) { if (course.getCourseId() == courseId) { removedCourse = course; break; } } if (removedCourse != null) { student.removeCourse(removedCourse); System.out.println("退课成功!"); } else { System.out.println("未找到该课程,请重新选择!"); } } else if (operation == 3) { student.displayCourses(); } else if (operation == 4) { System.out.println("退出系统"); break; } else { System.out.println("无效的操作,请重新选择!"); } } scanner.close(); } }
代码解析:
1、定义了一个Course
类,用于表示课程,包含课程名称和课程ID两个属性。
2、定义了一个Student
类,用于表示学生,包含学生姓名、学生ID和一个存储已选课程的列表,提供了添加课程、删除课程和显示已选课程的方法。
3、在main
方法中,首先创建了一些课程对象和一个学生对象,然后使用while
循环不断接收用户输入的操作,根据操作执行相应的功能。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/640598.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复