Student List for Course (25) cid=100000596

本文介绍了一个课程注册系统的实现方法,该系统能够处理大量学生选课数据,并按课程编号输出选择每门课程的学生名单及其数量。

题目描述:

Zhejiang University has 40000 students and provides 2500 courses. Now given the registered course list of each student, you are supposed to output the student name lists of all the courses.

输入:

Each input file contains one test case. For each case, the first line contains 2 numbers: N (<=40000), the total number of students, and K (<=2500), the total number of courses. Then N lines follow, each contains a student's name (3 capital English letters plus a one-digit number), a positive number C (<=20) which is the number of courses that this student has registered, and then followed by C course numbers. For the sake of simplicity, the courses are numbered from 1 to K. 

输出:

For each test case, print the student name lists of all the courses in increasing order of the course numbers. For each course, first print in one line the course number and the number of registered students, separated by a space. Then output the students' names in alphabetical order. Each name occupies a line. 

样例输入:

10 5
ZOE1 2 4 5
ANN0 3 5 2 1
BOB5 5 3 4 2 1 5
JOE4 1 2
JAY9 4 1 2 5 4
FRA8 3 4 2 5
DON2 2 4 5
AMY7 1 5
KAT3 3 5 4 2
LOR6 4 2 4 1 5

样例输出: 

 

1 4
ANN0
BOB5
JAY9
LOR6
2 7
ANN0
BOB5
FRA8
JAY9
JOE4
KAT3
LOR6
3 1
BOB5
4 7
BOB5
DON2
FRA8
JAY9
KAT3
LOR6
ZOE1
5 9
AMY7
ANN0
BOB5
DON2
FRA8
JAY9
KAT3
LOR6
ZOE1

思路:

使用一个vector<string> course_list[课程数量]来保存数据,其中第一维代表课程,第二维度存储选了这门课的学生姓名。

第一纬度下标-1就是课程号,例如保存选了1号课程学生姓名的vector可以用course_list[0]表示。在读取所有数据后,对每个第二维vector用sort进行排序然后输出。

我的解决方案: 

#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n,k,c,cur_course;
    string name;
    scanf("%d %d",&n,&k);
    vector<string> course_list[k];
    //course_list下标-1是课程号
    for(int i=0;i<n;i++) {
        cin >> name;
        cin >> c;
        for (int i = 0; i < c; i++) {
            scanf("%d", &cur_course);
            course_list[cur_course - 1].push_back(name);
        }
    }
    for(int i=0;i<k;i++){
        sort(course_list[i].begin(),course_list[i].end());
    }
    for(int i=0;i<k;i++){
        cout<<i+1<<' '<<course_list[i].size()<<endl;
        for(int j=0;j<course_list[i].size();j++){
            cout<<course_list[i][j]<<endl;
        }
    }

return 0;
}

 

package com.niit.servlet; import com.niit.pojo.StudentCourse; import com.niit.util.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import com.niit.mapper.StudentCourseMapper; import java.util.Map; import java.util.HashMap; import net.sf.json.JSONObject; @WebServlet("/student/enrollCourse") public class StudentCourseServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); Integer studentId = (Integer) session.getAttribute("studentId"); if (studentId == null) { JSONObject json = new JSONObject(); json.put("success", false); json.put("errorMsg", "请先登录!"); response.getWriter().write(json.toString()); return; } String action = request.getParameter("action"); // 退课功能 if ("withdraw".equals(action)) { String courseIds = request.getParameter("courseIds"); if (courseIds == null || courseIds.isEmpty()) { JSONObject json = new JSONObject(); json.put("success", false); json.put("errorMsg", "请选择要退选的课程!"); response.getWriter().write(json.toString()); return; } SqlSession sqlSession = MyBatisUtil.getSqlSession(); try { String[] courseIdArray = courseIds.split(","); for (String cid : courseIdArray) { Integer courseId = Integer.parseInt(cid); StudentCourseMapper studentCourseMapper = sqlSession.getMapper(StudentCourseMapper.class); int count = studentCourseMapper.checkEnrollmentByStudentAndCourse(studentId, courseId); if (count > 0) { // 移除重复声明,直接使用已存在的 studentCourseMapper 变量 com.niit.mapper.CourseMapper courseMapper = sqlSession.getMapper(com.niit.mapper.CourseMapper.class); // 删除选课记录 studentCourseMapper.deleteEnrollment(studentId, courseId); // 减少课程已选人数 sqlSession.update("com.niit.mapper.CourseMapper.decreaseEnrolledCount", courseId); } } sqlSession.commit(); JSONObject json = new JSONObject(); json.put("success", true); json.put("message", "退课成功!"); response.getWriter().write(json.toString()); } catch (Exception e) { sqlSession.rollback(); e.printStackTrace(); JSONObject json = new JSONObject(); json.put("success", false); json.put("errorMsg", "退课异常,请重试!\n" + e.getMessage()); response.getWriter().write(json.toString()); } finally { sqlSession.close(); } return; } // 选课功能(批量处理) String courseIds = request.getParameter("courseIds"); if (courseIds == null || courseIds.isEmpty()) { JSONObject json = new JSONObject(); json.put("success", false); json.put("errorMsg", "请选择要添加的课程!"); response.getWriter().write(json.toString()); return; } SqlSession sqlSession = MyBatisUtil.getSqlSession(); try { String[] courseIdArray = courseIds.split(","); StudentCourseMapper studentCourseMapper = sqlSession.getMapper(StudentCourseMapper.class); com.niit.mapper.CourseMapper courseMapper = sqlSession.getMapper(com.niit.mapper.CourseMapper.class); StringBuilder message = new StringBuilder(); boolean hasError = false; for (String cid : courseIdArray) { Integer courseId = Integer.parseInt(cid); int count = studentCourseMapper.checkEnrollmentByStudentAndCourse(studentId, courseId); if (count > 0) { message.append("课程ID: ").append(courseId).append(" 已选过,无法重复选课!\n"); hasError = true; continue; } // 检查课程容量 Map<String, Integer> paramMap = new HashMap<>(); paramMap.put("courseId", courseId); // 移除容量检查,直接更新选课人数并插入记录 sqlSession.update("com.niit.mapper.CourseMapper.updateEnrolledCount", paramMap); StudentCourse sc = new StudentCourse(); sc.setStudentId(studentId); sc.setCourseId(courseId); sqlSession.insert("com.niit.mapper.StudentCourseMapper.enrollCourse", sc); message.append("课程ID: ").append(courseId).append(" 选课成功!\n"); } sqlSession.commit(); JSONObject json = new JSONObject(); json.put("success", !hasError); json.put("message", message.toString()); response.getWriter().write(json.toString()); } catch (Exception e) { sqlSession.rollback(); e.printStackTrace(); JSONObject json = new JSONObject(); json.put("success", false); json.put("errorMsg", "选课异常,请重试!\n" + e.getMessage()); System.out.println("选课失败: " + e.getMessage()); response.getWriter().write(json.toString()); } finally { sqlSession.close(); System.out.println("选课操作会话已关闭"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Integer studentId = (Integer) session.getAttribute("studentId"); if (studentId == null) { response.sendRedirect("/login.jsp"); return; } // 获取可选课程列表并转发到选课页面 SqlSession sqlSession = MyBatisUtil.getSqlSession(); try { // 获取可选课程列表 request.setAttribute("selectCourseList", sqlSession.selectList("com.niit.mapper.CourseMapper.courseList")); // 获取已选课程列表 request.setAttribute("myCourseList", sqlSession.selectList("com.niit.mapper.StudentCourseMapper.getCoursesByStudentId", studentId)); } finally { sqlSession.close(); } request.getRequestDispatcher("/student/selectCourse.jsp").forward(request, response); } } <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.niit.mapper.StudentCourseMapper"> <select id="existStudentByStuId" parameterType="String" resultType="boolean"> SELECT COUNT(*) > 0 FROM t_student_course WHERE studentId = #{id} </select> <select id="hasScoreWithCourseId" parameterType="int" resultType="boolean"> SELECT COUNT(*) > 0 FROM t_student_course WHERE courseId = #{courseId} AND score IS NOT NULL </select> <select id="hasScoreByStudentId" parameterType="int" resultType="boolean"> SELECT COUNT(*) > 0 FROM t_student_course WHERE studentId = #{studentId} AND score IS NOT NULL </select> <select id="checkEnrollmentByStudentCourseId" resultType="int"> SELECT COUNT(*) FROM t_student_course WHERE studentId = #{studentId} AND courseId = #{courseId} </select> <delete id="deleteEnrollment"> DELETE FROM t_student_course WHERE studentId = #{studentId} AND courseId = #{courseId} </delete> <update id="decreaseEnrolledCount"> UPDATE t_course SET isxuan = isxuan - 1 WHERE id = #{courseId} </update> <update id="updateEnrolledCount"> <![CDATA[ UPDATE t_course SET isxuan = isxuan + 1 WHERE id = #{courseId} AND isxuan < coursetime ]]> </update> <insert id="createEnrollment" parameterType="com.niit.pojo.StudentCourse"> INSERT INTO t_student_course(studentId, courseId) VALUES(#{studentId}, #{courseId}) </insert> <select id="getCoursesByStudentId" resultType="com.niit.pojo.StudentCourse"> SELECT c.* FROM t_course c JOIN t_student_course sc ON c.id = sc.courseId WHERE sc.studentId = #{studentId} </select> <select id="findStudentsByTeacherId" resultType="com.niit.pojo.StudentCourse"> SELECT sc.*, s.trueName as studentName, c.courseName as courseName FROM t_student_course sc JOIN t_student s ON sc.studentId = s.id JOIN t_course c ON sc.courseId = c.id JOIN t_teacher t ON c.teacherId = t.id WHERE t.id = #{teacherId} </select> <update id="updateScore"> UPDATE t_student_course SET score = #{score} WHERE id = #{id} </update> <!-- 查询学生已选课程 --> <resultMap id="courseResultMap" type="com.niit.pojo.Course"> <result property="id" column="courseId"/> <result property="courseName" column="courseName"/> <result property="credit" column="credit"/> <result property="teacherId" column="teacherId"/> </resultMap> <select id="getEnrolledCoursesByStudentId" parameterType="int" resultMap="courseResultMap"> SELECT sc.courseId as courseId, c.courseName, c.credit, c.teacherId FROM t_student_course sc JOIN t_course c ON sc.courseId = c.id WHERE sc.studentId = #{studentId} </select> <!-- 检查学生是否已选该课程 --> <select id="checkEnrollmentByStudentAndCourse" parameterType="map" resultType="int"> SELECT COUNT(*) FROM t_student_course WHERE studentId = #{studentId} AND courseId = #{courseId} </select> <!-- 插入选课记录 --> <insert id="enrollCourse" parameterType="com.niit.pojo.StudentCourse"> INSERT INTO t_student_course (studentId, courseId) VALUES (#{studentId}, #{courseId}) </insert> <!-- 删除选课记录 --> <delete id="deleteEnrollmentByStudentAndCourse" parameterType="map"> DELETE FROM t_student_course WHERE studentId = #{studentId} AND courseId = #{courseId} </delete> <!-- 减少课程已选人数 --> <update id="decreaseEnrolledCountByCourseId"> UPDATE t_course SET isxuan = isxuan - 1 WHERE id = #{id} AND isxuan > 0 </update> <delete id="deleteEnrollmentByCourseId"> DELETE FROM t_student_course WHERE courseId = #{courseId} </delete> <delete id="deleteEnrollmentByStudentId" parameterType="int"> DELETE FROM t_student_course WHERE studentId = #{studentId} </delete> <!-- 根据教师ID查询学生 --> <select id="getStudentsByTeacherId" parameterType="int" resultType="com.niit.pojo.StudentCourse"> SELECT sc.id, sc.studentId, sc.courseId, sc.score, s.id as "student.id", s.trueName as "student.trueName", c.courseName as "course.courseName" FROM t_student_course sc JOIN t_student s ON sc.studentId = s.id JOIN t_course c ON sc.courseId = c.id WHERE c.teacherId = #{teacherId} </select> <!-- 检查课程是否存在 --> <select id="existsCourseByCourseId" parameterType="int" resultType="boolean"> SELECT COUNT(*) > 0 FROM t_course WHERE id = #{courseId} </select> <select id="login" parameterType="com.niit.pojo.User" resultType="com.niit.pojo.User"> SELECT * FROM t_manager WHERE t_manager.userName = #{userName} AND password = #{password} </select> </mapper> 修改代码使其实现选课和退课功能
07-10
import java.util.Scanner; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int type = sc.nextInt(); switch(type){ case 1: test1(sc);break; case 2: test2(sc);break; case 3: test3(sc);break; case 4: test4(sc); } } //test方法为(4)中情况,见上述说明 public static void test1(Scanner sc) { Student student1 = new Student(); Student student2 = new Student(); System.out.println("学生对象总数: " + Student.getStuNum()); } public static void test2(Scanner sc) { } public static void test3(Scanner sc) { } public static void test4(Scanner sc) { } } // 学生类Student class Student{ private int stuID; private String stuName; private static int stuNum ; public Student() { System.out.println("学生类无参构造方法"); } public Student(int stuID, String stuName) { System.out.println("学生类有参构造方法"); this.stuID =stuID ; this.stuName = stuName; } public int getStuID() { return stuID; } public String getStuName() { return stuName; } public static int getStuNum() { return stuNum; } public void setStuID(int stuID) { this.stuID = stuID; } public void setStuName(String stuName) { this.stuName = stuName; } } // 课程类Course class Course{ private int cID; private String cName; private int cNum ; public Course() { System.out.println("课程类无参构造方法"); } public Course(int cID, String cName) { System.out.println("课程类有参构造方法"); this.cID =cID ; this.cName = cName; } public int getcID() { return cID; } public String getcName() { return cName; } public int getcNum() { return cNum; } public void setcID(int cID) { this.cID = cID; } public void setcName(String cName) { this.cName = cName; } } // 学生选课类Schedule class Schedule{ private List<Student> stuList; private List<Course> cList; private int schNum; public Schedule() { stuList = new ArrayList<>(); cList = new ArrayList<>(); } public void addCourse(Student stu, Course course) { if (!stuList.contains(stu)) { stuList.add(stu);//检查stuList中是否有这个学生 } if (!cList.contains(course)) { cList.add(course);//检查cList是否包含这门课 } } // 显示学生选课详情方法 public void displayCourse() { for (Student stu : stuList) { System.out.println("学生 " + stu.getStuName() + " 的选课情况:"); for (Course course : cList) { System.out.println(" - " + course.getcName()); } } } }
10-24
import java.util.ArrayList; import java.util.List; // 学生类:封装基本信息并带字段校验 class Student { private String id; private String name; private String major; public Student(String id, String name, String major) { setId(id); setName(name); setMajor(major); } // 学号校验:非空且为纯数字 public void setId(String id) { if (id == null || id.trim().isEmpty()) { throw new IllegalArgumentException("学号必须是非空的正整数字符串"); } this.id = id; } public String getId() { return id; } // 姓名校验:非空 public void setName(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("姓名不能为空"); } this.name = name; } public String getName() { return name; } // 专业校验:非空 public void setMajor(String major) { if (major == null || major.trim().isEmpty()) { throw new IllegalArgumentException("专业不能为空"); } this.major = major; } public String getMajor() { return major; } } // 课程类 class Course { private String courseId; private String courseName; private double credits; public Course(String courseId, String courseName, double credits) { this.courseId = courseId; this.courseName = courseName; this.credits = credits; } public String getCourseId() { return courseId; } public String getCourseName() { return courseName; } public double getCredits() { return credits; } } // 成绩类:包含平时分、期末分、总评与绩点计算 class Grade { private double regularScore; private double finalScore; private double totalScore; public Grade(double regularScore, double finalScore) { this.regularScore = regularScore; this.finalScore = finalScore; this.totalScore = 0.3 * regularScore + 0.7 * finalScore; // 加权总评 } public double getTotalScore() { return totalScore; } // 绩点转换规则 public double getGPA() { if (totalScore >= 90) return 4.0; else if (totalScore >= 80) return 3.0; else if (totalScore >= 70) return 2.0; else if (totalScore >= 60) return 1.0; else return 0.0; } public double getRegularScore() { return regularScore; } public double getFinalScore() { return finalScore; } } // 学生管理类:使用 List 存储数据,通过遍历查找关联关系 class StudentManager { private List<Student> students = new ArrayList<>(); private List<Course> courses = new ArrayList<>(); private List<String> studentIds = new ArrayList<>(); // 对应成绩记录的学生ID private List<String> courseIds = new ArrayList<>(); // 对应成绩记录的课程ID private List<Grade> grades = new ArrayList<>(); // 成绩本体 // 添加学生(不允许重复学号) public void addStudent(Student s) { for (Student exist : students) { if (exist.getId().equals(s.getId())) { System.out.println("学号已存在:" + s.getId()); return; } } students.add(s); } // 添加课程 public void addCourse(Course c) { for (Course exist : courses) { if (exist.getCourseId().equals(c.getCourseId())) { System.out.println("课程编号已存在:" + c.getCourseId()); return; } } courses.add(c); } // 录入成绩(先查学生和课程是否存在) public void addGrade(String studentId, String courseId, double regular, double finalScore) { if (findStudentById(studentId) == null) { System.out.println("错误:找不到学号为 " + studentId + " 的学生"); return; } if (findCourseById(courseId) == null) { System.out.println("错误:找不到课程编号为 " + courseId + " 的课程"); return; } Grade grade = new Grade(regular, finalScore); studentIds.add(studentId); courseIds.add(courseId); grades.add(grade); } // 根据学号查找学生 private Student findStudentById(String id) { for (Student s : students) { if (s.getId().equals(id)) return s; } return null; } // 根据课程编号查找课程 private Course findCourseById(String id) { for (Course c : courses) { if (c.getCourseId().equals(id)) return c; } return null; } // 打印某学生成绩单 public void printTranscript(String studentId) { Student student = findStudentById(studentId); if (student == null) { System.out.println("未找到学生:" + studentId); return; } System.out.printf("\n【成绩单】\n姓名:%s\t学号:%s\t专业:%s\n", student.getName(), student.getId(), student.getMajor()); System.out.println("----------------------------------------"); boolean hasRecord = false; double totalCredits = 0.0; double totalWeightedGPA = 0.0; //判断第 i 条成绩记录是否属于当前查询的学生 for (int i = 0; i < studentIds.size(); i++) { if (studentIds.get(i).equals(studentId)) { hasRecord = true; //获取课程和成绩信息 String cid = courseIds.get(i); Course course = findCourseById(cid); Grade grade = grades.get(i); System.out.printf("%s %s: %.1f分 (平时%.1f 期末%.1f) → GPA=%.1f\n", course.getCourseId(), course.getCourseName(), grade.getTotalScore(), grade.getRegularScore(), grade.getFinalScore(), grade.getGPA()); //累计该学生所修课程的总学分 totalCredits += course.getCredits(); //计算“学分 × 绩点”的加权和 totalWeightedGPA += course.getCredits() * grade.getGPA(); } } //检查是否存在成绩记录 if (!hasRecord) { System.out.println("暂无成绩记录。"); } else if (totalCredits > 0) { //确保有有效学分才计算 GPA double avgGPA = totalWeightedGPA / totalCredits; System.out.printf("→ 平均绩点(GPA): %.2f\n", avgGPA); } System.out.println("========================================\n"); } } // 主类:测试系统功能 public class chengji { public static void main(String[] args) { StudentManager manager = new StudentManager(); // 添加学生(带校验) manager.addStudent(new Student("1234", "张三", "计算机科学")); manager.addStudent(new Student("2345", "李四", "数字媒体")); manager.addStudent(new Student("4567", "王五", "会计")); // 添加课程 manager.addCourse(new Course("CS101", "Java程序设计", 3.0)); manager.addCourse(new Course("CS102", "数据结构", 4.0)); manager.addCourse(new Course("CS103", "高等数学", 3.5)); // 录入成绩 manager.addGrade("1234", "CS101", 80, 73); manager.addGrade("1234", "CS102", 90, 88); manager.addGrade("1234", "CS103", 83, 80); manager.addGrade("2345", "CS101", 90, 94); manager.addGrade("2345", "CS102", 86, 80); manager.addGrade("2345", "CS103", 88, 90); manager.addGrade("4567", "CS101", 65, 60); manager.addGrade("4567", "CS102", 75, 70); manager.addGrade("4567", "CS103", 80, 75); // 输出成绩单 manager.printTranscript("1234"); manager.printTranscript("2345"); manager.printTranscript("4567"); } } 生成该代码的UML类图
09-26
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值