首页 > 其他分享 >BLOG-3

BLOG-3

时间:2023-06-23 17:35:33浏览次数:38  
标签:String grade BLOG parts student new matching

前言:

  这次博客是对之前发布的6-8次PTA题目集(成绩计算系列)的一次总结,经过前几次系列题目的磨练,相信对于认真写的同学来说这次成绩系列的题目也不是很难。只要肯花点时间,拿个及格不是问题。题量来说还是比较少的,对于一些高手来说,几个小时便可拿到高分。

设计与分析:

7-1 课程成绩统计程序-1

  类的设计老师已经大体讲过了,我的设计与老师的稍有不同,我的只有一个成绩类,如果是考核类型的课程,平时分就为0分。这些题目的主要难度就在于排序。排序的方法有好几种,如果使用恰当,可以大大提高程序效率。

这是源代码

import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

class Student{
    String student_num;
    String name;
    public Student(String student_num,String name){
        this.name=name;
        this.student_num=student_num;
    }
}

class Course{
    String name;
    String nature;
    String assessment;
    public Course(String name,String nature,String assessment){
        this.name=name;
        this.nature=nature;
        this.assessment=assessment;
    }
}
class Class{
    String num;
    ArrayList<Student> studentList=new ArrayList<>();
    public Class(String num){
        this.num=num;
    }
    public void Addstudent(Student student){
        studentList.add(student);
    }
}


class Grade{
    int regularscore;
    int finalscore;
    double totalscore;

    public Grade(int regularscore,int finalscore,int totalscore){
        this.regularscore=regularscore;
        this.finalscore=finalscore;
        this.totalscore=totalscore;
    }
}
class Matching{
    Student student;
    Course course;
    Grade grade;
    public Matching(Student student,Course course,Grade grade){
        this.student=student;
        this.course=course;
        this.grade=grade;
    }
}
class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        List<String> commands = new ArrayList<>(); // 存储用户输入的所有指令

        HashMap<String, Course> courseMap = new HashMap<>();
        List<Class> classList = new ArrayList<>();
        List<Matching> matchingList = new ArrayList<>();

        while (true) {
            String line = input.nextLine();
            if (line.equals("end")) {
                break;
            } else {
                commands.add(line); // 将输入存储起来
            }
        }
        input.close();

        // 遍历存储的所有指令,并执行相应操作
        Set<String> validCourseNatures = new HashSet<>(Arrays.asList("必修", "选修"));
        Set<String> validAssessments = new HashSet<>(Arrays.asList("考试", "考察"));
        Set<String> studentCoursePairs = new HashSet<>();

        for (String command : commands) {
            String[] parts = command.split(" ");
            if (parts.length >= 4) {
                String studentCoursePair = parts[0] + " " + parts[2];
                if (studentCoursePairs.contains(studentCoursePair)) {
                    continue;
                } else {
                    studentCoursePairs.add(studentCoursePair);
                }
            }

            if (command.matches("\\D+\\s\\D+\\s\\D+")&&validAssessments.contains(parts[2])&&validCourseNatures.contains(parts[1])&&parts[0].length() < 10) {

                if (parts[1].equals("必修") && parts[2].equals("考察")) {
                    System.out.println(parts[0] + " : course type & access mode mismatch");
                    continue;
                }else{
                    if(courseMap.get(parts[0])!=null){
                        continue;
                    }else{
                        Course course = new Course(parts[0], parts[1], parts[2]);
                        courseMap.put(parts[0], course);
                    }
                }

            } else if (command.matches("\\d+\\s\\D+\\s\\D+\\s\\d+\\s\\d+")&&isValid(Integer.parseInt(parts[4]),Integer.parseInt(parts[3]),parts[0],parts[1])) {

                Student student = new Student(parts[0], parts[1]);

                for (Class classlist : classList) {
                    if (classlist.num.equals(parts[0].substring(0, 6))) {
                        classlist.Addstudent(student);
                    }
                }

                if (courseMap.get(parts[2])!=null&&(courseMap.get(parts[2]).nature.equals("必修") || courseMap.get(parts[2]).assessment.equals("考试"))) {
                    Grade grade = new Grade(Integer.parseInt(parts[3]), Integer.parseInt(parts[4]), (int) (Integer.parseInt(parts[3]) * 0.3 + Integer.parseInt(parts[4]) * 0.7));
                    Matching matching = new Matching(student, courseMap.get(parts[2]), grade);
                    matchingList.add(matching);
                } else {
                    Grade grade = new Grade(0, 0, -1);
                    Matching matching = new Matching(student, courseMap.get(parts[0]), grade);
                    matchingList.add(matching);
                    if(courseMap.get(parts[2])==null){
                        System.out.println(parts[2] +" does not exist");
                    }else{
                        System.out.println(parts[0] + " " + parts[1] + " " + ": access mode mismatch");
                    }
                }

            } else if (command.matches("\\d+\\s\\D+\\s\\D+\\s\\d+")&&isValid(0,Integer.parseInt(parts[3]),parts[0],parts[1])) {
                Student student = new Student(parts[0], parts[1]);

                for (Class classlist : classList) {
                    if (classlist.num.equals(parts[0].substring(0, 6))) {
                        classlist.Addstudent(student);
                    }
                }

                if (courseMap.get(parts[2])!=null&&courseMap.get(parts[2]).nature.equals("选修")) {
                    Grade grade = new Grade(0, Integer.parseInt(parts[3]), (int) Integer.parseInt(parts[3]));
                    Matching matching = new Matching(student, courseMap.get(parts[2]), grade);
                    matchingList.add(matching);
                } else {
                    Grade grade = new Grade(0, 0, -1);
                    Matching matching = new Matching(student, courseMap.get(parts[0]), grade);
                    matchingList.add(matching);
                    if(courseMap.get(parts[2])==null){
                        System.out.println(parts[2] +" does not exist");
                    }else{
                        System.out.println(parts[0] + " " + parts[1] + " " + ": access mode mismatch");
                    }
                }

            } else {
                System.out.println("wrong format");
            }
        }

        //输出学生成绩
        Map<String, List<Matching>> studentToMatching = matchingList.stream().collect(Collectors.groupingBy(matching -> matching.student.student_num));
        List<Map.Entry<String, List<Matching>>> entries = new ArrayList<>(studentToMatching.entrySet());
        entries.sort((o1, o2) -> o1.getKey().compareTo(o2.getKey()));
        for (Map.Entry<String, List<Matching>> entry : entries) {
            String studentNum = entry.getKey();
            List<Matching> matchings = entry.getValue();
            double totalScoreAvg = matchings.stream().mapToDouble(matching -> matching.grade.totalscore).average().orElse(0);
            if(totalScoreAvg==-1){
                System.out.println(studentNum + " " + matchings.get(0).student.name + " did not take any exams");
            }else{
                System.out.println(studentNum + " " + matchings.get(0).student.name + " " + (int)totalScoreAvg);
            }

        }

        //输出课程平均成绩
        Map<String, List<Matching>> courseToMatching = matchingList.stream()
                .filter(matching -> matching.course != null) // 添加非空判断
                .collect(Collectors.groupingBy(matching -> matching.course.name));

        List<Map.Entry<String, List<Matching>>> entries2 = new ArrayList<>(courseToMatching.entrySet());
        entries2.sort((o1, o2) -> {
            Collator collator = Collator.getInstance(Locale.CHINA);
            return collator.compare(o1.getKey(), o2.getKey());
        });
        for (Map.Entry<String, List<Matching>> entry : entries2) {
            String courseName = entry.getKey();
            List<Matching> matchings = entry.getValue();
            double regularScoreAvg = matchings.stream().mapToInt(matching -> matching.grade.regularscore).average().orElse(0);
            double finalScoreAvg = matchings.stream().mapToInt(matching -> matching.grade.finalscore).average().orElse(0);
            double totalScoreAvg = matchings.stream().mapToDouble(matching -> matching.grade.totalscore).average().orElse(0);
            if(regularScoreAvg!=0){
                System.out.println(courseName + " " + (int)regularScoreAvg + " " + (int)finalScoreAvg + " " + (int)totalScoreAvg);
            }else if(totalScoreAvg!=0&&regularScoreAvg==0){
                System.out.println(courseName + " " + (int)finalScoreAvg + " " + (int)totalScoreAvg);
            }else if(totalScoreAvg==-1){
                System.out.println(courseName + " has no grades yet");
            }
        }
        for (String command : commands) {
            String[] parts = command.split(" ");
            if (parts.length == 3 && courseMap.containsKey(parts[0])) {
                if (courseToMatching.get(parts[0]) == null) {
                    System.out.println(parts[0] + " has no grades yet");
                }
            }
        }

        //输出班级平均成绩
        Map<String, List<Matching>> classToMatching = matchingList.stream().collect(Collectors.groupingBy(matching -> matching.student.student_num.substring(0, 6)));
        List<Map.Entry<String, List<Matching>>> entries1 = new ArrayList<>(classToMatching.entrySet());
        entries1.sort((o1, o2) -> {
            double avg1 = o1.getValue().stream().mapToDouble(matching -> matching.grade.totalscore).average().orElse(0);
            double avg2 = o2.getValue().stream().mapToDouble(matching -> matching.grade.totalscore).average().orElse(0);
            return Double.compare(avg2, avg1);
        });
        for (Map.Entry<String, List<Matching>> entry : entries1) {
            String classNum = entry.getKey();
            List<Matching> matchings = entry.getValue();
            double totalScoreAvg = matchings.stream().mapToDouble(matching -> matching.grade.totalscore).average().orElse(0);
            if(totalScoreAvg==-1){
                System.out.println(classNum + " has no grades yet");
            }else{
                System.out.println(classNum + " " + (int)totalScoreAvg);
            }
        }

    }

    public static boolean isValid(int score1,int score2, String studentId, String name) {
        if (score1 < 0 || score1 > 100) {
            return false;
        }
        if (score2 < 0 || score2 > 100) {
            return false;
        }
        if (studentId.length() != 8 || studentId.length()!=8){
            return false;
        }
        if (name.length() > 10) {
            return false;
        }
        return true;
    }

}

 

7-3 课程成绩统计程序-2

  这次题目相比于上次的改动并不算大,多了个 实验课成绩。还是比较好改动的。类的设计相比于上次并于改动。学生类中多了个成绩属性,用来储存学生的平均成绩。这次换了个排序方法。

这是源代码

import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

class Student {
    String student_num;
    String name;
    String averageScore;

    public Student(String student_num, String name, String averageScore) {
        this.name = name;
        this.student_num = student_num;
        this.averageScore = averageScore;
    }
}


class Course{
    String name;
    String nature;
    String assessment;
    public Course(String name,String nature,String assessment){
        this.name=name;
        this.nature=nature;
        this.assessment=assessment;
    }
}
class Class{
    String num;
    ArrayList<Student> studentList=new ArrayList<>();
    public Class(String num){
        this.num=num;
    }
    public void Addstudent(Student student){
        studentList.add(student);
    }
}


class Grade{
    int regularscore;
    int finalscore;
    double totalscore;

    public Grade(int regularscore,int finalscore,int totalscore){
        this.regularscore=regularscore;
        this.finalscore=finalscore;
        this.totalscore=totalscore;
    }
}
class Matching{
    Student student;
    Course course;
    Grade grade;
    public Matching(Student student,Course course,Grade grade){
        this.student=student;
        this.course=course;
        this.grade=grade;
    }
}
public class 成绩 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        List<String> commands = new ArrayList<>(); // 存储用户输入的所有指令

        HashMap<String, Course> courseMap = new HashMap<>();
        List<Class> classList = new ArrayList<>();
        List<Matching> matchingList = new ArrayList<>();

        while (true) {
            String line = input.nextLine();
            if (line.equals("end")) {
                break;
            } else {
                commands.add(line); // 将输入存储起来
            }
        }
        input.close();

        // 遍历存储的所有指令,并执行相应操作
        Set<String> validCourseNatures = new HashSet<>(Arrays.asList("必修", "选修","实验"));
        Set<String> validAssessments = new HashSet<>(Arrays.asList("考试", "考察","实验"));
        Set<String> studentCoursePairs = new HashSet<>();

        for (String command : commands) {
            String[] parts = command.split(" ");
            if (parts.length >= 4) {
                String studentCoursePair = parts[0] + " " + parts[2];
                if (studentCoursePairs.contains(studentCoursePair)) {
                    continue;
                } else {
                    studentCoursePairs.add(studentCoursePair);
                }
            }

            if (command.matches("\\D+\\s\\D+\\s\\D+") && validAssessments.contains(parts[2]) && validCourseNatures.contains(parts[1]) && parts[0].length() < 10) {

                if (parts[1].equals("必修") && parts[2].equals("考察")||!parts[1].equals("实验") && parts[2].equals("实验")) {
                    System.out.println(parts[0] + " : course type & access mode mismatch");
                    continue;
                } else {
                    if (courseMap.get(parts[0]) != null) {
                        continue;
                    } else {
                        Course course = new Course(parts[0], parts[1], parts[2]);
                        courseMap.put(parts[0], course);
                    }
                }

            } else if (command.matches("\\d+\\s\\D+\\s\\D+\\s\\d+\\s\\d+") && isValid(Integer.parseInt(parts[4]), Integer.parseInt(parts[3]), parts[0], parts[1],5)) {

                Student student = new Student(parts[0], parts[1],null);

                for (Class classlist : classList) {
                    if (classlist.num.equals(parts[0].substring(0, 6))) {
                        classlist.Addstudent(student);
                    }
                }

                if (courseMap.get(parts[2]) != null && (courseMap.get(parts[2]).nature.equals("必修") || courseMap.get(parts[2]).assessment.equals("考试"))) {
                    Grade grade = new Grade(Integer.parseInt(parts[3]), Integer.parseInt(parts[4]), (int) (Integer.parseInt(parts[3]) * 0.3 + Integer.parseInt(parts[4]) * 0.7));
                    Matching matching = new Matching(student, courseMap.get(parts[2]), grade);
                    matchingList.add(matching);
                } else {
                    Grade grade = new Grade(0, 0,-1 );
                    Matching matching = new Matching(student, courseMap.get(parts[0]), grade);
                    matchingList.add(matching);
                    if (courseMap.get(parts[2]) == null) {
                        System.out.println(parts[2] + " does not exist");
                    } else if(!courseMap.get(parts[2]).nature.equals("必修") || !courseMap.get(parts[2]).assessment.equals("考试")){
                        System.out.println(parts[0] + " " + parts[1] + " " + ": access mode mismatch");
                    }
                }

            } else if (command.matches("\\d+\\s\\D+\\s\\D+\\s\\d+") && isValid(0, Integer.parseInt(parts[3]), parts[0], parts[1],5)) {
                Student student = new Student(parts[0], parts[1],null);

                for (Class classlist : classList) {
                    if (classlist.num.equals(parts[0].substring(0, 6))) {
                        classlist.Addstudent(student);
                    }
                }

                if (courseMap.get(parts[2]) != null && courseMap.get(parts[2]).nature.equals("选修")) {
                    Grade grade = new Grade(0, Integer.parseInt(parts[3]), (int) Integer.parseInt(parts[3]));
                    Matching matching = new Matching(student, courseMap.get(parts[2]), grade);
                    matchingList.add(matching);
                } else {
                    Grade grade = new Grade(0, 0, -1);
                    Matching matching = new Matching(student, courseMap.get(parts[0]), grade);
                    matchingList.add(matching);
                    if (courseMap.get(parts[2]) == null) {
                        System.out.println(parts[2] + " does not exist");
                    } else if(!courseMap.get(parts[2]).nature.equals("选修")){
                        System.out.println(parts[0] + " " + parts[1] + " " + ": access mode mismatch");
                    }
                }

            }else if(courseMap.containsKey(parts[2]) && courseMap.get(parts[2]).nature.equals("实验")&&isValid(0,0,parts[0],parts[1],Integer.parseInt(parts[3]))){
                Student student = new Student(parts[0], parts[1],null);
                int total=0;
                boolean flag=true;

                for (Class classlist : classList) {
                    if (classlist.num.equals(parts[0].substring(0, 6))) {
                        classlist.Addstudent(student);
                    }
                }


                if (courseMap.get(parts[2]) != null && courseMap.get(parts[2]).nature.equals("实验")&&parts.length==Integer.parseInt(parts[3])+4) {

                    for(int i=4;i< parts.length;i++){
                        if(Integer.parseInt(parts[i])<0||Integer.parseInt(parts[i])>100){
                            Grade grade = new Grade(0, 0, -1);
                            Matching matching = new Matching(student, courseMap.get(parts[2]), grade);
                            System.out.println("worng format");
                            flag=false;continue;
                        }else {
                            total+= Integer.parseInt(parts[i]);
                        }
                    }
                    if(flag==false)continue;

                    Grade grade = new Grade(0, 0, total/Integer.parseInt(parts[3]));
                    Matching matching = new Matching(student, courseMap.get(parts[2]), grade);
                    matchingList.add(matching);
                } else {
                    Grade grade = new Grade(0, 0, -1);
                    Matching matching = new Matching(student, courseMap.get(parts[0]), grade);
                    matchingList.add(matching);
                    if (courseMap.get(parts[2]) == null) {
                        System.out.println(parts[2] + " does not exist");
                    } else if(parts.length!=Integer.parseInt(parts[3])+4){
                        System.out.println(parts[0] + " " + parts[1] + " " + ": access mode mismatch");
                    }else if(Integer.parseInt(parts[3])<4||Integer.parseInt(parts[3])>9){
                        System.out.println("wrong format");
                    }
                }

            }else {
                System.out.println("wrong format");
            }
        }

        //输出学生所有课程平均分
        printStudentAverageGrades(matchingList);
        printCourseAndClassAverageGrades(courseMap, matchingList);
    }
    public static boolean isValid(int score1,int score2, String studentId, String name,int num) {
        if (score1 < 0 || score1 > 100) {
            return false;
        }
        if (score2 < 0 || score2 > 100) {
            return false;
        }
        if (studentId.length() != 8 || !studentId.matches("\\d{8}")) {
            return false;
        }
        if (name.length() > 10) {
            return false;
        }
        if(num>9||num<4){
            return false;
        }
        return true;
    }

    public static void printStudentAverageGrades(List<Matching> matchingList) {
        Map<String, List<Matching>> studentMap = new HashMap<>();
        for (Matching matching : matchingList) {
            String studentId = matching.student.student_num;
            if (!studentMap.containsKey(studentId)) {
                studentMap.put(studentId, new ArrayList<>());
            }
            studentMap.get(studentId).add(matching);
        }

        List<Student> students = new ArrayList<>();
        for (String studentId : studentMap.keySet()) {
            List<Matching> matchings = studentMap.get(studentId);
            double totalScore = 0;
            int courseCount = 0;
            for (Matching matching : matchings) {
                if (matching.grade.totalscore >= 0) {
                    totalScore += matching.grade.totalscore;
                    courseCount++;
                }
            }
            double averageScore = courseCount == 0 ? -1 : totalScore / courseCount;
            Student student = matchings.get(0).student;
            students.add(new Student(student.student_num, student.name, averageScore < 0 ? "did not take any exams" : String.valueOf((int) averageScore)));

        }

        students.sort(Comparator.comparing(s -> s.student_num));
        for (Student student : students) {
            System.out.println(student.student_num + " " + student.name + " " + student.averageScore);
        }
    }

    public static void printCourseAndClassAverageGrades(Map<String, Course> courseMap, List<Matching> matchingList) {
        Map<String, List<Matching>> courseMatchings = new HashMap<>();
        for (Matching matching : matchingList) {
            if (matching.course != null) {
                Course course = courseMap.get(matching.course.name);
                String courseName = matching.course.name;
                if (!courseMatchings.containsKey(courseName)) {
                    courseMatchings.put(courseName, new ArrayList<>());
                }
                courseMatchings.get(courseName).add(matching);
            }
        }

        List<Course> courses = new ArrayList<>(courseMap.values());
        courses.sort(Comparator.comparing(c -> c.name));
        for (Course course : courses) {
            if (!courseMatchings.containsKey(course.name)) {
                System.out.println(course.name + " has no grades yet");
                continue;
            }
            List<Matching> matchings = courseMatchings.get(course.name);
            if (course.nature.equals("实验")) {
                double totalScore = 0;
                int studentCount = 0;
                for (Matching matching : matchings) {
                    if (matching.grade.totalscore >= 0) {
                        totalScore += matching.grade.totalscore;
                        studentCount++;
                    }
                }
                double averageScore = studentCount == 0 ? -1 : totalScore / studentCount;
                System.out.println(course.name + " " + (averageScore < 0 ? "has no grades yet" : (int) averageScore));
            } else {
                double totalRegularScore = 0;
                double totalFinalScore = 0;
                double totalScore = 0;
                int studentCount = 0;
                for (Matching matching : matchings) {
                    if (matching.grade.totalscore >= 0) {
                        totalRegularScore += matching.grade.regularscore;
                        totalFinalScore += matching.grade.finalscore;
                        totalScore += matching.grade.totalscore;
                        studentCount++;
                    }
                }
                double averageRegularScore = studentCount == 0 ? -1 : totalRegularScore / studentCount;
                double averageFinalScore = studentCount == 0 ? -1 : totalFinalScore / studentCount;
                double averageScore = studentCount == 0 ? -1 : totalScore / studentCount;
                if (averageRegularScore == 0) {
                    System.out.println(course.name + " " + (averageFinalScore < 0 ? "has no grades yet" : (int) averageFinalScore) + " " + (averageScore < 0 ? "has no grades yet" : (int) averageScore));
                } else {
                    System.out.println(course.name + " " + (averageRegularScore < 0 ? "has no grades yet" : (int) averageRegularScore) + " " + (averageFinalScore < 0 ? "has no grades yet" : (int) averageFinalScore) + " " + (averageScore < 0 ? "has no grades yet" : (int) averageScore));
                }
            }
        }

        Map<String, List<Matching>> classMatchings = new HashMap<>();
        for (Matching matching : matchingList) {
            String classNum = matching.student.student_num.substring(0, 6);
            if (!classMatchings.containsKey(classNum)) {
                classMatchings.put(classNum, new ArrayList<>());
            }
            classMatchings.get(classNum).add(matching);
        }

        List<String> classNums = new ArrayList<>(classMatchings.keySet());
        classNums.sort(Comparator.naturalOrder());
        for (String classNum : classNums) {
            List<Matching> matchings = classMatchings.get(classNum);
            double totalScore = 0;
            int studentCount = 0;
            for (Matching matching : matchings) {
                if (matching.grade.totalscore >= 0) {
                    totalScore += matching.grade.totalscore;
                    studentCount++;
                }
            }
            double averageScore = studentCount == 0 ? -1 : totalScore / studentCount;
            System.out.println(classNum + " " + (averageScore < 0 ? "has no grades yet" : (int) averageScore));
        }
    }
}

 

7-2 课程成绩统计程序-3

这次题目相比于上次修改了实验课的记录方式,还有可以改动考试课的权重。依旧是输入层面的改动。这次在课程类中添加了一个数组,用来储存权重。

以下是源代码

import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

class Student {
    String student_num;
    String name;
    String averageScore;
    public Student(String student_num, String name, String averageScore) {
        this.name = name;
        this.student_num = student_num;
        this.averageScore = averageScore;
    }
}


class Course{
    String name;
    String nature;
    String assessment;
    int i=10;
    double[] weight=new double[i];
    public Course(String name,String nature,String assessment){
        this.name=name;
        this.nature=nature;
        this.assessment=assessment;
    }

    public void initWeight(int size) {
        weight = new double[size];
    }
}
class Class{
    String num;
    ArrayList<Student> studentList=new ArrayList<>();
    public Class(String num){
        this.num=num;
    }
    public void Addstudent(Student student){
        studentList.add(student);
    }
}


class Grade{
    int regularscore;
    int finalscore;
    double totalscore;

    public Grade(int regularscore,int finalscore,double totalscore){
        this.regularscore=regularscore;
        this.finalscore=finalscore;
        this.totalscore=totalscore;
    }
}
class Matching{
    Student student;
    Course course;
    Grade grade;
    public Matching(Student student,Course course,Grade grade){
        this.student=student;
        this.course=course;
        this.grade=grade;
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        List<String> commands = new ArrayList<>(); // 存储用户输入的所有指令

        HashMap<String, Course> courseMap = new HashMap<>();
        List<Class> classList = new ArrayList<>();
        List<Matching> matchingList = new ArrayList<>();

        while (true) {
            String line = input.nextLine();
            if (line.equals("end")) {
                break;
            } else {
                commands.add(line); // 将输入存储起来
            }
        }
        input.close();

        // 遍历存储的所有指令,并执行相应操作
        Set<String> validCourseNatures = new HashSet<>(Arrays.asList("必修", "选修","实验"));
        Set<String> validAssessments = new HashSet<>(Arrays.asList("考试", "考察","实验"));
        Set<String> studentCoursePairs = new HashSet<>();

        for (String command : commands) {
            String[] parts = command.split(" ");
            if (parts.length >= 4) {
                String studentCoursePair = parts[0] + " " + parts[2];
                if (studentCoursePairs.contains(studentCoursePair)) {
                    continue;
                } else {
                    studentCoursePairs.add(studentCoursePair);
                }
            }

            if (validAssessments.contains(parts[2]) && validCourseNatures.contains(parts[1]) && parts[0].length() < 10) {

                if (parts[1].equals("必修") && parts[2].equals("考察")||!parts[1].equals("实验") && parts[2].equals("实验")) {
                    System.out.println(parts[0] + " : course type & access mode mismatch");
                    continue;
                }
                if((parts[2].equals("实验")&&(Integer.parseInt(parts[3])<=3&&Integer.parseInt(parts[3])>=10))){
                    continue;
                }
                if(parts[1].equals("必修")||parts[2].equals("考试")){
                    if(courseMap.get(parts[1])==null){
                        Course course = new Course(parts[0], parts[1], parts[2]);
                        course.weight[0]=Double.parseDouble(parts[3]);
                        course.initWeight(2);course.i=2;
                        course.weight[1]=Double.parseDouble(parts[3]);
                        double sum=course.weight[0]+course.weight[1];
                        if(sum!=1.0){
                            System.out.println(parts[0] + " weight value error");
                            continue;
                        }
                        courseMap.put(parts[0], course);
                    }else{
                        continue;
                    }
                }
                else if(parts[2].equals("考察")){
                    if(courseMap.get(parts[0])==null){
                        Course course = new Course(parts[0], parts[1], parts[2]);
                        courseMap.put(parts[0], course);
                    }else{
                        continue;
                    }
                }
                else if(parts[2].equals("实验")){
                    if(parts.length!=4+Integer.parseInt(parts[3])){
                        System.out.println(parts[0] + " : number of scores does not match");
                        continue;
                    }else if(courseMap.get(parts[1])==null){
                        Course course = new Course(parts[0], parts[1], parts[2]);
                        course.initWeight(Integer.parseInt(parts[3]));double sum=0;
                        course.i=Integer.parseInt(parts[3]);
                        for(int j=0;j<Integer.parseInt(parts[3]);j++){
                            course.weight[j]=Double.parseDouble(parts[4+j]);
                            sum+=Double.parseDouble(parts[4+j]);
                        }
                        if(sum!=1.0){
                            System.out.println(parts[0] + " : weight value error");
                            continue;
                        }
                        courseMap.put(parts[0], course);
                    }else{
                        continue;
                    }
                }

            } else if (command.matches("\\d+\\s\\D+\\s\\D+\\s\\d+\\s\\d") && isValid(Integer.parseInt(parts[4]), Integer.parseInt(parts[3]), parts[0], parts[1],5)) {

                Student student = new Student(parts[0], parts[1],null);

                for (Class classlist : classList) {
                    if (classlist.num.equals(parts[0].substring(0, 6))) {
                        classlist.Addstudent(student);
                    }
                }

                if (courseMap.get(parts[2]) != null && (courseMap.get(parts[2]).nature.equals("必修") || courseMap.get(parts[2]).assessment.equals("考试"))) {
                    Grade grade = new Grade(Integer.parseInt(parts[3]), Integer.parseInt(parts[4]), (int) ((Integer.parseInt(parts[3]) * courseMap.get(parts[2]).weight[0] + Integer.parseInt(parts[4]) * courseMap.get(parts[2]).weight[0])));
                    Matching matching = new Matching(student, courseMap.get(parts[2]), grade);
                    matchingList.add(matching);
                } else {
                    Grade grade = new Grade(0, 0,-1 );
                    Matching matching = new Matching(student, courseMap.get(parts[0]), grade);
                    matchingList.add(matching);
                    if (courseMap.get(parts[2]) == null) {
                        System.out.println(parts[0]+" "+parts[1]+" "+parts[2] + " : does not exist");
                    } else if(courseMap.get(parts[2]) != null&&!courseMap.get(parts[2]).nature.equals("必修") || !courseMap.get(parts[2]).assessment.equals("考试")){
                        System.out.println(parts[0] + " " + parts[1] + " " + ": access mode mismatch");
                    }
                }

            } else if (command.matches("\\d+\\s\\D+\\s\\D+\\s\\d") && isValid(0, Integer.parseInt(parts[3]), parts[0], parts[1],5)) {
                Student student = new Student(parts[0], parts[1],null);

                for (Class classlist : classList) {
                    if (classlist.num.equals(parts[0].substring(0, 6))) {
                        classlist.Addstudent(student);
                    }
                }

                if (courseMap.get(parts[2]) != null && courseMap.get(parts[2]).nature.equals("选修")) {
                    Grade grade = new Grade(0, Integer.parseInt(parts[3]), (int) Integer.parseInt(parts[3]));
                    Matching matching = new Matching(student, courseMap.get(parts[2]), grade);
                    matchingList.add(matching);
                } else {
                    Grade grade = new Grade(0, 0, -1);
                    Matching matching = new Matching(student, courseMap.get(parts[0]), grade);
                    matchingList.add(matching);
                    if (courseMap.get(parts[2]) == null) {
                        System.out.println(parts[0]+" "+parts[1]+" "+parts[2] + " : does not exist");
                    } else if(!courseMap.get(parts[2]).nature.equals("选修")){
                        System.out.println(parts[0] + " " + parts[1] + " " + ": access mode mismatch");
                    }
                }

            }else if(courseMap.containsKey(parts[2]) && courseMap.get(parts[2]).nature.equals("实验")&&isValid(0,0,parts[0],parts[1],courseMap.get(parts[2]).i )){
                Student student = new Student(parts[0], parts[1],null);
                double total=0;
                boolean flag=true;

                for (Class classlist : classList) {
                    if (classlist.num.equals(parts[0].substring(0, 6))) {
                        classlist.Addstudent(student);
                    }
                }


                if (courseMap.get(parts[2]) != null && courseMap.get(parts[2]).nature.equals("实验")&&parts.length==3+courseMap.get(parts[2]).i) {

                    for(int i=3;i< parts.length;i++){
                        if(Integer.parseInt(parts[i])<0||Integer.parseInt(parts[i])>100){
                            Grade grade = new Grade(0, 0, -1);
                            Matching matching = new Matching(student, courseMap.get(parts[2]), grade);
                            System.out.println("worng format");
                            flag=false;continue;
                        }else {
                            total+= Integer.parseInt(parts[i])*courseMap.get(parts[2]).weight[i-3];
                        }
                    }
                    if(flag==false){
                        continue;
                    }

                    Grade grade = new Grade(0, 0, (int)total);
                    Matching matching = new Matching(student, courseMap.get(parts[2]), grade);
                    matchingList.add(matching);
                } else {
                    Grade grade = new Grade(0, 0, -1);
                    Matching matching = new Matching(student, courseMap.get(parts[0]), grade);
                    matchingList.add(matching);
                    if (courseMap.get(parts[2]) == null) {
                        System.out.println(parts[0]+" "+parts[1]+" "+parts[2] + " : does not exist");
                    } else if(parts.length!=3+courseMap.get(parts[2]).i){
                        System.out.println(parts[0] + " " + parts[1] + " " + ": access mode mismatch");
                    }
                }

            } else if (courseMap.get(parts[2])==null) {
                System.out.println(parts[0]+" "+parts[1]+" "+parts[2] + " : does not exist");
            } else {
                System.out.println("wrong format");
            }
        }

        //输出学生所有课程平均分
        printStudentAverageGrades(matchingList);
        printCourseAndClassAverageGrades(courseMap, matchingList);
    }
    public static boolean isValid(int score1,int score2, String studentId, String name,int num) {
        if (score1 < 0 || score1 > 100) {
            return false;
        }
        if (score2 < 0 || score2 > 100) {
            return false;
        }
        if (studentId.length() != 8 || !studentId.matches("\\d{8}")) {
            return false;
        }
        if (name.length() > 10) {
            return false;
        }
        if(num > 9 || num < 4){
            return false;
        }
        return true;
    }

    public static void printStudentAverageGrades(List<Matching> matchingList) {
        Map<String, List<Matching>> studentMap = new HashMap<>();
        for (Matching matching : matchingList) {
            String studentId = matching.student.student_num;
            if (!studentMap.containsKey(studentId)) {
                studentMap.put(studentId, new ArrayList<>());
            }
            studentMap.get(studentId).add(matching);
        }

        List<Student> students = new ArrayList<>();
        for (String studentId : studentMap.keySet()) {
            List<Matching> matchings = studentMap.get(studentId);
            double totalScore = 0;
            int courseCount = 0;
            for (Matching matching : matchings) {
                if (matching.grade.totalscore >= 0) {
                    totalScore += matching.grade.totalscore;
                    courseCount++;
                }
            }
            double averageScore = courseCount == 0 ? -1 : totalScore / courseCount;
            Student student = matchings.get(0).student;
            students.add(new Student(student.student_num, student.name, averageScore < 0 ? "did not take any exams" : String.valueOf((int) averageScore)));

        }

        students.sort(Comparator.comparing(e -> e.student_num));
        for (Student student : students) {
            System.out.println(student.student_num + " " + student.name + " " + student.averageScore);
        }
    }

    public static void printCourseAndClassAverageGrades(Map<String, Course> courseMap, List<Matching> matchingList) {
        Map<String, List<Matching>> courseMatchings = new HashMap<>();
        for (Matching matching : matchingList) {
            if (matching.course != null) {
                Course course = courseMap.get(matching.course.name);
                String courseName = matching.course.name;
                if (!courseMatchings.containsKey(courseName)) {
                    courseMatchings.put(courseName, new ArrayList<>());
                }
                courseMatchings.get(courseName).add(matching);
            }
        }

        List<Course> courses = new ArrayList<>(courseMap.values());
        courses.sort(Comparator.comparing(e  -> e.name));
        for (Course course : courses) {
            if (!courseMatchings.containsKey(course.name)) {
                System.out.println(course.name + " has no grades yet");
                continue;
            }
            List<Matching> matchings = courseMatchings.get(course.name);
            if (course.nature.equals("实验")) {
                double totalScore = 0;
                int studentCount = 0;
                for (Matching matching : matchings) {
                    if (matching.grade.totalscore >= 0) {
                        totalScore += matching.grade.totalscore;
                        studentCount++;
                    }
                }
                double averageScore = studentCount == 0 ? -1 : totalScore / studentCount;
                System.out.println(course.name + " " + (averageScore < 0 ? "has no grades yet" : (int) averageScore));
            } else {
                double totalRegularScore = 0;
                double totalFinalScore = 0;
                double totalScore = 0;
                int studentCount = 0;
                for (Matching matching : matchings) {
                    if (matching.grade.totalscore >= 0) {
                        totalRegularScore += matching.grade.regularscore;
                        totalFinalScore += matching.grade.finalscore;
                        totalScore += matching.grade.totalscore;
                        studentCount++;
                    }
                }
                double averageRegularScore = studentCount == 0 ? -1 : totalRegularScore / studentCount;
                double averageFinalScore = studentCount == 0 ? -1 : totalFinalScore / studentCount;
                double averageScore = studentCount == 0 ? -1 : totalScore / studentCount;
                if (averageRegularScore == 0) {
                    System.out.println(course.name + " "+ (averageScore < 0 ? "has no grades yet" : (int) averageScore));
                } else {
                    System.out.println(course.name +" " + (averageScore < 0 ? "has no grades yet" : (int) averageScore));
                }
            }
        }

        Map<String, List<Matching>> classMatchings = new HashMap<>();
        for (Matching matching : matchingList) {
            String classNum = matching.student.student_num.substring(0, 6);
            if (!classMatchings.containsKey(classNum)) {
                classMatchings.put(classNum, new ArrayList<>());
            }
            classMatchings.get(classNum).add(matching);
        }

        List<String> classNums = new ArrayList<>(classMatchings.keySet());
        classNums.sort(Comparator.naturalOrder());
        for (String classNum : classNums) {
            List<Matching> matchings = classMatchings.get(classNum);
            double totalScore = 0;
            int studentCount = 0;
            for (Matching matching : matchings) {
                if (matching.grade.totalscore >= 0) {
                    totalScore += matching.grade.totalscore;
                    studentCount++;
                }
            }
            double averageScore = studentCount == 0 ? -1 : totalScore / studentCount;
            System.out.println(classNum + " " + (averageScore < 0 ? "has no grades yet" : (int) averageScore));
        }
    }
}

采坑心得:

  这系列题目的难度主要在于给数据进行计算和排序,需要写比较多的代码。还有一些要注意的地方。首先,在修改类结构时,要注意将原来的继承关系改为组合关系。其次,在输入课程信息时,要注意输入的课程性质和考核方式是否匹配。此外,在输入实验课程信息时,要注意输入的分项成绩数量值和分项成绩权重的个数是否匹配。最后,在解析考试课、实验课时,要检查分项成绩权重值的总和是否等于1。

改进建议:

排序时可以使用一些简单的方法去简化排序所要写的代码,如lambda表达式。举个列子

public static void printCourseAndClassAverageGrades(Map<String, Course> courseMap, List<Matching> matchingList) {
        Map<String, List<Matching>> courseMatchings = new HashMap<>();
        for (Matching matching : matchingList) {
            if (matching.course != null) {
                Course course = courseMap.get(matching.course.name);
                String courseName = matching.course.name;
                if (!courseMatchings.containsKey(courseName)) {
                    courseMatchings.put(courseName, new ArrayList<>());
                }
                courseMatchings.get(courseName).add(matching);
            }
        }

        List<Course> courses = new ArrayList<>(courseMap.values());
        courses.sort(Comparator.comparing(e  -> e.name));
        for (Course course : courses) {
            if (!courseMatchings.containsKey(course.name)) {
                System.out.println(course.name + " has no grades yet");
                continue;
            }
            List<Matching> matchings = courseMatchings.get(course.name);
            if (course.nature.equals("实验")) {
                double totalScore = 0;
                int studentCount = 0;
                for (Matching matching : matchings) {
                    if (matching.grade.totalscore >= 0) {
                        totalScore += matching.grade.totalscore;
                        studentCount++;
                    }
                }
                double averageScore = studentCount == 0 ? -1 : totalScore / studentCount;
                System.out.println(course.name + " " + (averageScore < 0 ? "has no grades yet" : (int) averageScore));
            } else {
                double totalRegularScore = 0;
                double totalFinalScore = 0;
                double totalScore = 0;
                int studentCount = 0;
                for (Matching matching : matchings) {
                    if (matching.grade.totalscore >= 0) {
                        totalRegularScore += matching.grade.regularscore;
                        totalFinalScore += matching.grade.finalscore;
                        totalScore += matching.grade.totalscore;
                        studentCount++;
                    }
                }
                double averageRegularScore = studentCount == 0 ? -1 : totalRegularScore / studentCount;
                double averageFinalScore = studentCount == 0 ? -1 : totalFinalScore / studentCount;
                double averageScore = studentCount == 0 ? -1 : totalScore / studentCount;
                if (averageRegularScore == 0) {
                    System.out.println(course.name + " "+ (averageScore < 0 ? "has no grades yet" : (int) averageScore));
                } else {
                    System.out.println(course.name +" " + (averageScore < 0 ? "has no grades yet" : (int) averageScore));
                }
            }
        }

        Map<String, List<Matching>> classMatchings = new HashMap<>();
        for (Matching matching : matchingList) {
            String classNum = matching.student.student_num.substring(0, 6);
            if (!classMatchings.containsKey(classNum)) {
                classMatchings.put(classNum, new ArrayList<>());
            }
            classMatchings.get(classNum).add(matching);
        }

        List<String> classNums = new ArrayList<>(classMatchings.keySet());
        classNums.sort(Comparator.naturalOrder());
        for (String classNum : classNums) {
            List<Matching> matchings = classMatchings.get(classNum);
            double totalScore = 0;
            int studentCount = 0;
            for (Matching matching : matchings) {
                if (matching.grade.totalscore >= 0) {
                    totalScore += matching.grade.totalscore;
                    studentCount++;
                }
            }
            double averageScore = studentCount == 0 ? -1 : totalScore / studentCount;
            System.out.println(classNum + " " + (averageScore < 0 ? "has no grades yet" : (int) averageScore));
        }
    }

 

在代码中,课程列表 courses 使用了 Collections.sort() 方法进行排序,传入了一个 lambda 表达式作为比较器,按照课程名称的字典顺序进行排序。班级号列表 classNums 也使用了 Collections.sort() 方法进行排序,传入了 Comparator.naturalOrder() 作为比较器,按照班级号的自然顺序进行排序。

总结:

  通过这几次作业,我还是自学到了挺多东西的如lambda表达式,非常实用,许多地方都可以用到。还有Collections类的用法,排序时非常方便。

标签:String,grade,BLOG,parts,student,new,matching
From: https://www.cnblogs.com/wsdjb/p/17499401.html

相关文章

  • Blog-3
    (1).前言:(总结之前所涉及到的知识点、题量、难度等情况)一7-1课程成绩统计程序-1难度:对我来说,难,难,难,写这个我花了好长时间,分析了很久很久,但是要比较的话,菜单要更难,还是我太菜了。知识点:1.集合类:代码使用了多种集合类,如'ArrayList'、'HashMap'和'LinkedHashMap',用于存储和管理......
  • 最后一次Blog
    BLOG: 1.前言:最后几周的PTA难度明显上升,需要设计的类更多,尤其是学生成绩录入系统。还更考察对集合的使用,如Map,Set集合,利用他们自动排序去重的功能,完成题目.难度呈递增趋势。自己还是太菜,许多题目就没有拿到满分。随着本次的博客作业到来也预示着我的本学期的Java课程也......
  • BLOG-3
    一、前言先叠个甲,针对上次互评同学们的评论,我这次虽说也写上了题目,但我写了一万多字,真的没有水字数!!而且也没用ChatGPT写,麻烦各位帅哥美女给高点分儿,我也保证在互评时都打90分以上。1.知识点:LinkedHashMap和HashMap是有区别的,前者是按插入顺序储存元素,后者是哈希表排序会在后面......
  • blog
    importjava.text.Collator;importjava.util.*;classCourse{Stringname;Stringtype;Stringmode;Course(Stringname,Stringtype,Stringmode){this.name=name;this.type=type;this.mode=mode;}}classGrade{......
  • 2023-06-20 hexo博客 运行报错:Cannot find module 'hexo' from 'D:\ablog' 提示要rm
    前言:把博客拉到到新电脑,运行hexos报错如下:PSD:\ablog>hexosERRORCannotfindmodule'hexo'from'D:\ablog'ERRORLocalhexoloadingfailedinD:\ablogERRORTryrunning:'rm-rfnode_modules&&npminstall--force'原因:没有装......
  • BUUCTF:[CFI-CTF 2018]webLogon capture
    https://buuoj.cn/challenges#[CFI-CTF%202018]webLogon%20capturelogon.pcapng包的数量很少,随便抓个包跟踪一下流即可发现passwordPSC:\Users\Administrator>php-r"var_dump(urldecode('%20%43%46%49%7b%31%6e%73%33%63%75%72%33%5f%6c%30%67%30%6e%7d%20'));"Co......
  • BLOG-3
    通过对最后三次大作业中的题目集的学习,我有以下心得:1.三次题目集的知识点我觉得有这些(1):输入语句的使用。  (2):java中多个if()判断语句的使用。(3):java中的if()和else语句的嵌套使用。......
  • weblogic学习笔记
    前言工作原因,在weblogic上部署了一个很重要的服务。虽然部署成功了,但是对该weblogic还不是很了解。市面上中文资料少之又少,而且讲解的weblogic版本已经很老旧,对新人不是很友好。借着这个机会,打算系统学习下weblogic,也将学习的内容与大家进行分享。本文章weblogic版本为12.2.1.4......
  • Hello CN-Blog!
    你好,标题!你好,正文。这是我的第一篇测试博客。print('你好,代码块')你好无序列表\[\int_{-\inf}^{+\inf}{\text{你好,公式}}\]......
  • linux系统nfs搭建-cnblog
    Linux系统nfs搭建首先介绍一下NFS:​ NFS(NetworkFileSystem)即网络文件系统,是FreeBSD支持的文件系统中的一种,它允许网络中的计算机之间通过TCP/IP网络共享资源。在NFS的应用中,本地NFS的客户端应用可以透明地读写位于远端NFS服务器上的文件,就像访问本地文件一样。1、虚拟机nfs环......