Blog作业3

第九次作业
7-1 统计Java程序中关键词的出现次数
作者 段喜龙
单位 南昌航空大学
编写程序统计一个输入的Java源码中关键字(区分大小写)出现的次数。说明如下:

Java中共有53个关键字(自行百度)
从键盘输入一段源码,统计这段源码中出现的关键字的数量
注释中出现的关键字不用统计
字符串中出现的关键字不用统计
统计出的关键字及数量按照关键字升序进行排序输出
未输入源码则认为输入非法
输入格式:

输入Java源码字符串,可以一行或多行,以exit行作为结束标志

输出格式:

当未输入源码时,程序输出Wrong Format
当没有统计数据时,输出为空
当有统计数据时,关键字按照升序排列,每行输出一个关键字及数量,格式为数量\t关键字
输入样例:

在这里给出一组输入。例如:


//Test public method
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
exit

输出样例:

在这里给出相应的输出。例如:


1 float
3 if
2 int
2 new
2 public
3 this
2 throw

 

 

 

 代码:


import java.util.*;

public class Main {
static Scanner sc = new Scanner(System.in);
static TreeMap<String, Integer> treeMap;

public static void main(String[] args) {
initializeKeywords();
processInput();
printKeywordCounts();
}

static void initializeKeywords() {
StringBuilder stringBuilder = new StringBuilder("abstract、assert、boolean、break、byte、case、catch、char、class、continue、default、do、double、else、enum、extends、final、finally、float、for、if、implements、import、int、interface、instanceof、long、native、new、package、private、protected、public、return、short、static、strictfp、super、switch、synchronized、this、throw、throws、transient、try、void、volatile、while、goto、const、true、false、null");
String[] keywords = stringBuilder.toString().split("\\、");
treeMap = new TreeMap<>();
for (String s : keywords) {
treeMap.put(s, 0);
}
}

static void processInput() {
boolean isEmpty = true;
int index2 = -1, index3 = -1, flag = 0; //注释2标记
int index4 = -1; //引用标记

while (true) {
StringBuilder temp = new StringBuilder(sc.nextLine());
int index1 = temp.indexOf("//");
if (temp.toString().contains("\"")) {
index4 = temp.indexOf("\"") + 1;
if (index4 + 1 < temp.length()) {
while (temp.toString().charAt(index4) != '\"') {
temp.delete(index4, index4 + 1);
if (index4 + 1 >= temp.length())
break;
}
}
if (index4 + 1 < temp.length())
temp.delete(index4, index4 + 1);
}
if (temp.toString().contains("/*"))
index2 = temp.indexOf("/*");
if (temp.toString().contains("*/")) {
index3 = temp.indexOf("*/");
}
if (index2 != 0 && index3 != 0 && !temp.toString().contains("/*")) {
flag = 1;
}
if (index1 != -1) {
temp.replace(index1, temp.length(), "");
}
if (index2 != -1) {
if (index3 != -1) {
temp.replace(index2, index3 + 2, "");
index2 = -1;
index3 = -1;
flag = 0;
} else {
if (flag == 0)
temp.replace(index2, temp.length(), "");
else if (flag == 1)
temp.replace(0, temp.length(), "");
continue;
}
}
String[] strings = temp.toString().split("[^]a-zA-Z=\\-\\*+/\\^]+");
for (String s : strings) {
if (treeMap.containsKey(s)) {
treeMap.replace(s, treeMap.get(s) + 1);
}
}
if (temp.toString().equals("exit")) {
if (isEmpty) {
System.out.println("Wrong Format");
return;
} else
break;
}
isEmpty = false;
}
}

static void printKeywordCounts() {
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
Integer integer = entry.getValue();
if (integer != 0) {
System.out.println(integer + "\t" + entry.getKey());
}
}
}
}

 

import java.util.*;

public class Main {
static Scanner sc = new Scanner(System.in);
static TreeMap<String, Integer> treeMap;

public static void main(String[] args) {
initializeKeywords();
processInput();
printKeywordCounts();
}

static void initializeKeywords() {
StringBuilder stringBuilder = new StringBuilder("abstract、assert、boolean、break、byte、case、catch、char、class、continue、default、do、double、else、enum、extends、final、finally、float、for、if、implements、import、int、interface、instanceof、long、native、new、package、private、protected、public、return、short、static、strictfp、super、switch、synchronized、this、throw、throws、transient、try、void、volatile、while、goto、const、true、false、null");
String[] keywords = stringBuilder.toString().split("\\、");
treeMap = new TreeMap<>();
for (String s : keywords) {
treeMap.put(s, 0);
}
}

static void processInput() {
boolean isEmpty = true;
int index2 = -1, index3 = -1, flag = 0; //注释2标记
int index4 = -1; //引用标记

while (true) {
StringBuilder temp = new StringBuilder(sc.nextLine());
int index1 = temp.indexOf("//");
if (temp.toString().contains("\"")) {
index4 = temp.indexOf("\"") + 1;
if (index4 + 1 < temp.length()) {
while (temp.toString().charAt(index4) != '\"') {
temp.delete(index4, index4 + 1);
if (index4 + 1 >= temp.length())
break;
}
}
if (index4 + 1 < temp.length())
temp.delete(index4, index4 + 1);
}
if (temp.toString().contains("/*"))
index2 = temp.indexOf("/*");
if (temp.toString().contains("*/")) {
index3 = temp.indexOf("*/");
}
if (index2 != 0 && index3 != 0 && !temp.toString().contains("/*")) {
flag = 1;
}
if (index1 != -1) {
temp.replace(index1, temp.length(), "");
}
if (index2 != -1) {
if (index3 != -1) {
temp.replace(index2, index3 + 2, "");
index2 = -1;
index3 = -1;
flag = 0;
} else {
if (flag == 0)
temp.replace(index2, temp.length(), "");
else if (flag == 1)
temp.replace(0, temp.length(), "");
continue;
}
}
String[] strings = temp.toString().split("[^]a-zA-Z=\\-\\*+/\\^]+");
for (String s : strings) {
if (treeMap.containsKey(s)) {
treeMap.replace(s, treeMap.get(s) + 1);
}
}
if (temp.toString().equals("exit")) {
if (isEmpty) {
System.out.println("Wrong Format");
return;
} else
break;
}
isEmpty = false;
}
}

static void printKeywordCounts() {
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
Integer integer = entry.getValue();
if (integer != 0) {
System.out.println(integer + "\t" + entry.getKey());
}
}
}
}

7-1 统计Java程序中关键词的出现次数

 

 代码:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
StringBuilder a = new StringBuilder();
Map map=new TreeMap();
String[] gjc = {"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while"};
String kg,exit="exit";
int i,n,flag=0;

kg = x.nextLine();
while( !kg.equals(exit)) {
a.append(kg.replaceAll("//.*", " ").replaceAll("\".*\"", " "));//去掉"//"后和的内容以及双引号里的内容
kg = x.nextLine();
flag=1;
}
String b = a.toString().replaceAll("/\\*\\s*.*\\s*\\*/", " ");//去掉"/* */"里的内容,放入字符串b中
if(flag==0) {
System.out.println("Wrong Format");
}

// 循环找每个关键词出现的次数
for(i=0;i< gjc.length;i++) {
Pattern pattern = Pattern.compile("\\b"+gjc[i]+"\\b");//创建关键词的正则表达式
Matcher matcher = pattern.matcher(b);//字符串与关键词匹配
n=0;
while(matcher.find()) {//找到该关键词的话,记录该关键词的次数
n++;
}
if(n!=0){//把次数不是0的关键词替换为次数
map.put(gjc[i], n);
}
}
String map1= String.valueOf(map);//把map转化为字符串map1
//System.out.println(map1);
String map2=map1.replace("{","").replace("}","");
//System.out.println(map2);
String[] map3=map2.split(", ");
for (i=0;i< map3.length;i++){
String[] map4=map3[i].split("=");
System.out.println(map4[1]+"\t"+map4[0]);
}
}
}

 

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

代码:

复制代码
import java.util.*;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Objects;
class Course implements Comparable<Course>{
    String name;
    int type;//0为必修,1为选修
    int mode=0;//0为考试,1为考察
    public Course(String name, int type, int mode) {
        this.name = name;
        this.type = type;
        this.mode = mode;
    }
    public Course(String name,int type){
        this.name=name;
        this.type=type;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Course course = (Course) o;
        return Objects.equals(name, course.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public int compareTo(Course o) {
        return Collator.getInstance(Locale.CHINA).compare(this.name, o.name);
    }
}
class CourseSelection {
    Course course;
    Student student;
    Score score;

    public CourseSelection(Course course, Student student, Score score) {
        this.course = course;
        this.student = student;
        this.score = score;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CourseSelection that = (CourseSelection) o;
        return Objects.equals(course, that.course) && Objects.equals(student, that.student);
    }

    @Override
    public int hashCode() {
        return Objects.hash(course, student);
    }
}
class ExamineScore extends Score{
    @Override
    Integer getScore() {
        return this.finalScore;
    }
    public ExamineScore(){
        type=1;
    }
}
class ExamScore extends Score{
    @Override
    Integer getScore() {
        return (int)( this.usualScore*0.3+this.finalScore*0.7);
    }
    public ExamScore(){
        type=0;
    }
}
abstract class Score {
    Integer finalScore=0;
    int type;
    Integer usualScore=0;
    abstract Integer getScore();
}
class Student implements Comparable<Student>{
    String id;
    String name;
    public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public int compareTo(Student s) {
        return this.id.compareTo(s.id);
    }
}
public class Main {
    public static void main(String[]args){
        Scanner scanner=new Scanner(System.in);
        HashSet<CourseSelection>courseSelectionHashSet=new HashSet<>();
        HashSet<String>courseNameSet=new HashSet<>();
        HashMap<Student,Boolean>studentScorehashMap=new HashMap<>();
        TreeMap<Student,Integer>averageStudentScore=new TreeMap<>();//综合
        TreeMap<Course,Integer>courseUsualAverage=new TreeMap<>();//平时
        TreeMap<Course,Integer>courseFinalAverage=new TreeMap<>();//期末
        TreeMap<Course,Integer>courseTotalAverage=new TreeMap<>();//结合
        TreeMap<String,Integer>classTotalAverage=new TreeMap<>();//班级
        while(true){
            String temp=scanner.nextLine();
            if(temp.equals("end")){
                break;
            }
            String[] s = temp.split(" ");
            if(s[0].matches("[0-9]{0,100}")){
                if(s.length!=5&&s.length!=4){
                    System.out.println("wrong format");
                    continue;
                }
                Student student=new Student(s[0],s[1]);
                Course course=null;
                if(s[3].contains(".")){
                    System.out.println("wrong format");
                    continue;
                }else if(s.length==5&&s[4].contains(".")){
                    System.out.println("wrong format");
                    continue;
                }
                if(s[0].length()!=8||s[1].length()>10||s[2].length()>10||Integer.parseInt(s[3])<0||Integer.parseInt(s[3])>100){
                    System.out.println("wrong format");
                    continue;
                }else if(s.length==5&&((Integer.parseInt(s[4])<0)||(Integer.parseInt(s[4])>100))){
                    System.out.println("wrong format");
                    continue;
                }
                if(courseNameSet.contains(s[2])){
                    for(Course tempCourse:courseUsualAverage.keySet()){
                        if(tempCourse.name.equals(s[2]))
                        {course=tempCourse;break;}
                    }
                }else {
                    System.out.println(s[2]+" does not exist");
                    averageStudentScore.put(student,0);
                    classTotalAverage.put(s[0].substring(0,6),0);
                    continue;
                }
                Score score=new ExamScore();
                if(s.length==4&&course.mode==1){
                    score=new ExamineScore();
                    score.finalScore=Integer.parseInt(s[3]);
                }else if(s.length==5&&course.mode==0){
                    score=new ExamScore();
                    score.usualScore=Integer.parseInt(s[3]);score.finalScore=Integer.parseInt(s[4]);
                }
                classTotalAverage.put(s[0].substring(0,6),0);
                if((s.length==4&&course.mode==0)||(s.length==5&&course.mode==1)){
                    System.out.println(s[0]+" "+s[1]+" "+": access mode mismatch");
                    averageStudentScore.put(student,0);
                    continue;
                }

                //获取每个同学,以便计算平均分
                averageStudentScore.put(student,0);
                CourseSelection courseSelection=new CourseSelection(course,student,score);
                courseSelectionHashSet.add(courseSelection);
            }else{
                if(s.length!=3&&s.length!=2){
                    System.out.println("wrong format");
                    continue;
                }
                if((s.length==3)&&(s[0].length()>10||(!s[1].equals("必修")&&!s[1].equals("选修"))||(!s[2].equals("考试")&&!s[2].equals("考察")))){
                    System.out.println("wrong format");
                    continue;
                }else if((s.length==2)&&(s[0].length()>10||!s[1].equals("必修"))){
                    System.out.println("wrong format");
                    continue;
                }
                Course course=new Course(s[0],s[1].equals("必修")?0:1);
                if(s.length==3)
                    course.mode=s[2].equals("考试")?0:1;
                if(course.type==0&&course.mode==1){
                    System.out.println(s[0]+" : course type & access mode mismatch");
                    continue;
                }
                courseUsualAverage.put(course,0);
                courseFinalAverage.put(course,0);
                courseTotalAverage.put(course,0);
                courseNameSet.add(s[0]);
            }
        }
        //平均成绩,排序
        for (Student student : averageStudentScore.keySet()) {
            List<Integer> list = new ArrayList<>();
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.student.id.equals(student.id)) {
                    list.add(courseSelection.score.getScore());
                }
            }

            for (Integer tempScore : list) {
                averageStudentScore.replace(student, averageStudentScore.get(student) + tempScore);
            }
            if(list.size()!=0)
                averageStudentScore.replace(student, averageStudentScore.get(student) / list.size());
            if (list.size() == 0) {
                studentScorehashMap.put(student,false);
                System.out.println(student.id + " " + student.name + " " + "did not take any exams");
            }else {
                studentScorehashMap.put(student,true);
                System.out.println(student.id + " " + student.name + " " + averageStudentScore.get(student));
            }
        }
        //计算每门课程的平均 平时分,期末分,综合分
        for(Course course:courseUsualAverage.keySet()){
            List<Integer>list=new ArrayList<>();
            List<Integer>list1=new ArrayList<>();
            List<Integer>list2=new ArrayList<>();
            //平时分
            for(CourseSelection courseSelection:courseSelectionHashSet){
                if(courseSelection.course.name.equals(course.name)){
                    list.add(courseSelection.score.usualScore);
                }
            }
            //期末
            for(CourseSelection courseSelection:courseSelectionHashSet){
                if(courseSelection.course.name.equals(course.name)){
                    list1.add(courseSelection.score.finalScore);
                }
            }
            //综合
            for(CourseSelection courseSelection:courseSelectionHashSet){
                if(courseSelection.course.name.equals(course.name)){
                    list2.add(courseSelection.score.getScore());
                }
            }
            for(Integer tempScore:list){
                courseUsualAverage.replace(course,courseUsualAverage.get(course)+tempScore);
            }
            for(Integer tempScore:list1){
                courseFinalAverage.replace(course,courseFinalAverage.get(course)+tempScore);
            }
            for(Integer tempScore:list2){
                courseTotalAverage.replace(course,courseTotalAverage.get(course)+tempScore);
            }
            if(list.size()!=0)
                courseUsualAverage.replace(course,courseUsualAverage.get(course)/list.size());
            if(list1.size()!=0)
                courseFinalAverage.replace(course,courseFinalAverage.get(course)/list1.size());
            if(list2.size()!=0)
                courseTotalAverage.replace(course,courseTotalAverage.get(course)/list2.size());
            if(list.size()==0){
                System.out.println(course.name+" has no grades yet");
            }else{
                if(course.mode==0)
                    System.out.println(course.name+" "+courseUsualAverage.get(course)+" "+courseFinalAverage.get(course)+" "+courseTotalAverage.get(course));
                else
                    System.out.println(course.name+" "+courseFinalAverage.get(course)+" "+courseTotalAverage.get(course));
            }
        }
        //3.计算班级的分数
        for(String classId:classTotalAverage.keySet()){
            int sum=0;//人数
            boolean flag=false;//班级是否有分数记录
            for(Student student:averageStudentScore.keySet()){
                if(student.id.substring(0,6).equals(classId)){
                    classTotalAverage.replace(classId,classTotalAverage.get(classId)+averageStudentScore.get(student));
                    if(studentScorehashMap.get(student)){
                        flag=true;
                        sum++;
                    }
                }
            }
            if(sum!=0)
                classTotalAverage.replace(classId,classTotalAverage.get(classId)/sum);
            if(flag){
                System.out.println(classId+" "+classTotalAverage.get(classId));
            }else{
                System.out.println(classId+" "+"has no grades yet");
            }
        }
    }
}

类图:

 

部分代码缺乏注释,不够详细说明代码的作用和实现逻辑,给阅读代码的人理解带来一定困扰。部分变量命名不够语义化,不利于代码的理解和维护,

但代码结构清晰,使用了类和对象来表示学生、课程、选课和成绩等概念,提高了代码的可读性和可维护性。使用了合适的数据结构来存储数据,如HashSet、HashMap和TreeMap等,便于快速查找和操作数据。

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

代码:

代码:

 

复制代码
import java.util.*;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Objects;

class Course implements Comparable<Course>{
    protected String name;
    protected int type;//0为必修,1为选修,2为实验
    protected int mode=0;//0为考试,1为考察,2为实验
    public Course(String name, int type, int mode) {
        this.name = name;
        this.type = type;
        this.mode = mode;
    }
    public Course(String name){
        this.name=name ;
    };
    public Course(String name,int type){
        this.name=name;
        this.type=type;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Course course = (Course) o;
        return Objects.equals(name, course.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public int compareTo(Course o) {
        return Collator.getInstance(Locale.CHINA).compare(this.name, o.name);
    }
}
class CourseSelection {
    protected Course course;
    protected Student student;
    protected Grade grade;

    public CourseSelection(Course course, Student student, Grade grade) {
        this.course = course;
        this.student = student;
        this.grade = grade;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CourseSelection that = (CourseSelection) o;
        return Objects.equals(course, that.course) && Objects.equals(student, that.student);
    }
    @Override
    public int hashCode() {
        return Objects.hash(course, student);
    }

}
class ExamineGrade extends Grade{
    @Override
    Integer getGrade() {
        return this.finalGrade;
    }
    public ExamineGrade(){
        type=1;
    }
}
class ExamScore extends Grade{
    @Override
    Integer getGrade() {
        return (int)( this.usualGrade*0.3+this.finalGrade*0.7);
    }
    public ExamScore(){
        type=0;
    }
}
class ExperimentalScore extends Grade{
    Integer getGrade(){
        Integer result=0;
        for(Integer integer:experimentalGrades){
            result+=integer;
        }
        return result/experimentalGrades.size();
    }
}
abstract class Grade {
    protected Integer finalGrade=0;
    protected int type;
    protected Integer usualGrade=0;
    protected ArrayList<Integer>experimentalGrades=new ArrayList<>();
    abstract Integer getGrade();
}
class Student implements Comparable<Student>{
    protected String id;
    protected String name;

    public Student() {
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public int compareTo(Student s) {
        return this.id.compareTo(s.id);
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        HashSet<CourseSelection> courseSelectionHashSet = new HashSet<>();
        HashSet<String> courseNameSet = new HashSet<>();
        HashMap<Student, Boolean> studentScorehashMap = new HashMap<>();
        TreeMap<Student,Integer>averageStudentScore=new TreeMap<>();//综合
        TreeMap<Course,Integer>courseUsualAverage=new TreeMap<>();//平时
        TreeMap<Course,Integer>courseFinalAverage=new TreeMap<>();//期末
        TreeMap<Course,Integer>courseTotalAverage=new TreeMap<>();//结合
        TreeMap<String,Integer>classTotalAverage=new TreeMap<>();//班级
        while (true) {
            String temp = scanner.nextLine();
            if (temp.equals("end")) {
                break;
            }
            String[] s = temp.split(" ");
            if (s[0].matches("[0-9]{0,100}")) {
                Student student = new Student(s[0], s[1]);
                Course course = null;
                if(s.length>=5) {
                    int flag = 0;
                    for (int i = 4; i < s.length; i++) {
                        if (!s[i].matches("[0-9]{1,3}")) {
                            System.out.println("wrong format");
                            flag = 1;
                            break;
                        } else if (Integer.parseInt(s[i]) < 0 || Integer.parseInt(s[i]) > 100) {
                            System.out.println("wrong format");
                            flag = 1;
                            break;
                        }
                    }
                    if (flag == 1)
                        continue;
                }
                if (s[0].length() != 8 || s[1].length() > 10 || s[2].length() > 10 || !s[3].matches("[0-9]{1,3}") || (Integer.parseInt(s[3]) < 0 || Integer.parseInt(s[3]) > 100)) {
                    System.out.println("wrong format");
                    continue;
                }
                if (courseNameSet.contains(s[2])) {
                    for (Course tempCourse : courseUsualAverage.keySet()) {
                        if (tempCourse.name.equals(s[2])) {
                            course = tempCourse;
                            break;
                        }
                    }
                }
                if (s.length == 5 && ((Integer.parseInt(s[4]) < 0) || (Integer.parseInt(s[4]) > 100))) {
                    System.out.println("wrong format");
                    continue;
                } else if(course!=null&&course.mode==2){
                    if (!s[3].matches("[4-9]")) {
                        System.out.println("wrong format");
                        continue;
                    }
                    if (s.length != Integer.parseInt(s[3]) + 4) {
                        System.out.println(s[0] + " " + s[1] + " " + ": access mode mismatch");
                        classTotalAverage.put(s[0].substring(0, 6), 0);
                        averageStudentScore.put(student, 0);
                        continue;
                    }
                }

                if(!courseNameSet.contains(s[2])) {
                    System.out.println(s[2] + " does not exist");
                    averageStudentScore.put(student, 0);
                    classTotalAverage.put(s[0].substring(0, 6), 0);
                    continue;
                }
                Grade grade = new ExamScore();
                if (s.length == 4 && course.mode == 1) {
                    grade = new ExamineGrade();
                    grade.finalGrade = Integer.parseInt(s[3]);
                } else if (s.length == 5 && course.mode == 0) {
                    grade = new ExamScore();
                    grade.usualGrade = Integer.parseInt(s[3]);
                    grade.finalGrade = Integer.parseInt(s[4]);
                } else if (course.mode == 2) {
                    grade = new ExperimentalScore();
                    for (int i = 4; i < s.length; i++) {
                        grade.experimentalGrades.add(Integer.parseInt(s[i]));
                    }
                }
                classTotalAverage.put(s[0].substring(0, 6), 0);
                if ((s.length == 4 && course.mode == 0) || (s.length == 5 && course.mode == 1)) {
                    System.out.println(s[0] + " " + s[1] + " " + ": access mode mismatch");
                    averageStudentScore.put(student, 0);
                    continue;
                }

                //获取每个同学,以便计算平均分
                averageStudentScore.put(student, 0);
                CourseSelection courseSelection = new CourseSelection(course, student, grade);
                courseSelectionHashSet.add(courseSelection);
            } else {
                if (s.length != 3 && s.length != 2) {
                    System.out.println("wrong format");
                    continue;
                }
                if ((s.length == 3) && (s[0].length() > 10 || ((!s[1].equals("必修") && !s[1].equals("选修") && !s[1].equals("实验")) || (!s[2].equals("考试") && !s[2].equals("考察") && !s[2].equals("实验"))))) {
                    System.out.println("wrong format");
                    continue;
                } else if ((s.length == 2) && (s[0].length() > 10 || !s[1].equals("必修"))) {
                    System.out.println("wrong format");
                    continue;
                }
                int type = 0;
                //选择
                if (s[1].equals("必修")) type = 0;
                if (s[1].equals("选修")) type = 1;
                if (s[1].equals("实验")) type = 2;
                Course course = new Course(s[0], type);
                if (s.length == 3) {
                    int mode = 0;
                    if (s[2].equals("考试")) mode = 0;
                    if (s[2].equals("考察")) mode = 1;
                    if (s[2].equals("实验")) mode = 2;
                    course.mode = mode;
                }
                if ((course.type == 0 && course.mode == 1) || (course.mode == 2 && course.type != 2) || course.type == 2 && course.mode != 2) {
                    System.out.println(s[0] + " : course type & access mode mismatch");
                    continue;
                }
                courseUsualAverage.put(course, 0);
                courseFinalAverage.put(course, 0);
                courseTotalAverage.put(course, 0);
                courseNameSet.add(s[0]);
            }
        }
        //courseSelectionHashSet.stream().map(s->s.course.name).forEach(System.out::println);
        //1.求每个同学平均成绩,排序打印
        for (Student student : averageStudentScore.keySet()) {
            List<Integer> list = new ArrayList<>();
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.student.id.equals(student.id)) {
                    list.add(courseSelection.grade.getGrade());
                }
            }
            //List<Integer> list = courseSelectionHashSet.stream().filter(s -> s.student.id.equals(student.id)).map(s -> s.grade.getGrade()).toList();
            for (Integer tempScore : list) {
                averageStudentScore.replace(student, averageStudentScore.get(student) + tempScore);
            }
            if (list.size() != 0)
                averageStudentScore.replace(student, averageStudentScore.get(student) / list.size());
            if (list.size() == 0) {
                studentScorehashMap.put(student, false);
                System.out.println(student.id + " " + student.name + " " + "did not take any exams");
            } else {
                studentScorehashMap.put(student, true);
                System.out.println(student.id + " " + student.name + " " + averageStudentScore.get(student));
            }
        }
        //每门课程的平均 平时分,期末分,综合分
        for (Course course : courseUsualAverage.keySet()) {
            List<Integer> list = new ArrayList<>();
            List<Integer> list1 = new ArrayList<>();
            List<Integer> list2 = new ArrayList<>();
            //平时分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list.add(courseSelection.grade.usualGrade);
                }
            }
            //期末分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list1.add(courseSelection.grade.finalGrade);
                }
            }
            //综合分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list2.add(courseSelection.grade.getGrade());
                }
            }
for (Integer tempScore : list) { courseUsualAverage.replace(course, courseUsualAverage.get(course) + tempScore); } for (Integer tempScore : list1) { courseFinalAverage.replace(course, courseFinalAverage.get(course) + tempScore); } for (Integer tempScore : list2) { courseTotalAverage.replace(course, courseTotalAverage.get(course) + tempScore); } if (list.size() != 0) courseUsualAverage.replace(course, courseUsualAverage.get(course) / list.size()); if (list1.size() != 0) courseFinalAverage.replace(course, courseFinalAverage.get(course) / list1.size()); if (list2.size() != 0) courseTotalAverage.replace(course, courseTotalAverage.get(course) / list2.size()); if (list.size() == 0) { System.out.println(course.name + " has no grades yet"); } else { if (course.mode == 0) System.out.println(course.name + " " + courseUsualAverage.get(course) + " " + courseFinalAverage.get(course) + " " + courseTotalAverage.get(course)); else if(course.mode!=2) System.out.println(course.name + " " + courseFinalAverage.get(course) + " " + courseTotalAverage.get(course)); else System.out.println(course.name +" "+ courseTotalAverage.get(course)); } } //计算班级的分数 for (String classId : classTotalAverage.keySet()) { int sum = 0;//人数 boolean flag = false;//班级是否有分数记录 for (Student student : averageStudentScore.keySet()) { if (student.id.substring(0, 6).equals(classId)) { classTotalAverage.replace(classId, classTotalAverage.get(classId) + averageStudentScore.get(student)); if (studentScorehashMap.get(student)) { flag = true; sum++; } } } if (sum != 0) classTotalAverage.replace(classId, classTotalAverage.get(classId) / sum); if (flag) { System.out.println(classId + " " + classTotalAverage.get(classId)); } else { System.out.println(classId + " " + "has no grades yet"); } } } }
类图:

 代码注释比较清晰,对于关键部分的功能和逻辑有所说明;实现了对学生和课程的基本操作,包括添加学生、添加课程、录入成绩等,并能计算和打印学生、课程和班级的平均分数。但缺少异常处理机制,没有对输入和运行过程中的异常情况进行处理和恢复

 

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

代码:

代码:

复制代码
import java.util.*;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Objects;

class Course implements Comparable<Course>{
     String name;
     int type;//0为必修,1为选修,2为实验
     int mode=0;//0为考试,1为考察,2为实验
    public Course(String name, int type, int mode) {
        this.name = name;
        this.type = type;
        this.mode = mode;
    }
    public Course(String name){
        this.name=name ;
    };
    public Course(String name,int type){
        this.name=name;
        this.type=type;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Course course = (Course) o;
        return Objects.equals(name, course.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public int compareTo(Course o) {
        return Collator.getInstance(Locale.CHINA).compare(this.name, o.name);
    }
}
class CourseSelection {
     Course course;
     Student student;
     Grade grade;

    public CourseSelection(Course course, Student student, Grade grade) {
        this.course = course;
        this.student = student;
        this.grade = grade;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CourseSelection that = (CourseSelection) o;
        return Objects.equals(course, that.course) && Objects.equals(student, that.student);
    }
    @Override
    public int hashCode() {
        return Objects.hash(course, student);
    }

}
class ExamineGrade extends Grade{
    @Override
    Integer getGrade() {
        return this.finalGrade;
    }
    public ExamineGrade(){
        type=1;
    }
}
class ExamScore extends Grade{
    @Override
    Integer getGrade() {
        if(weight.size()!=0)
            return (int)( this.usualGrade* weight.get(0)+this.finalGrade*weight.get(1));
        return (int)( this.usualGrade* 0.3+this.finalGrade*0.7);
    }
    public ExamScore(){
        type=0;
    }
}
class ExperimentalScore extends Grade{
    Integer getGrade(){
        float result=0;
        for(int i=0;i<experimentalGrades.size();i++){
            result+=experimentalGrades.get(i)* weight.get(i);
        }
        return (int)result;
    }
}
abstract class Grade {
     Integer finalGrade=0;
     int type;
     Integer usualGrade=0;
     ArrayList<Integer>experimentalGrades=new ArrayList<>();
     ArrayList<Float>weight=new ArrayList<>();
    abstract Integer getGrade();
}
class Student implements Comparable<Student>{
     String id;
     String name;

    public Student() {
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public int compareTo(Student s) {
        return this.id.compareTo(s.id);
    }

}
public  class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        HashSet<CourseSelection> courseSelectionHashSet = new HashSet<>();
        HashSet<String> courseNameSet = new HashSet<>();
        HashMap<Student, Boolean> studentScorehashMap = new HashMap<>();
        TreeMap<Student, Integer> averageStudentScore = new TreeMap<>();
        TreeMap<Course, Integer> courseUsualAverage = new TreeMap<>();
        TreeMap<Course, Integer> courseFinalAverage = new TreeMap<>();
        TreeMap<Course, Integer> courseTotalAverage = new TreeMap<>();
        TreeMap<String, Integer> classTotalAverage = new TreeMap<>();
        TreeMap<Course, ArrayList<Float>> scoreWeight = new TreeMap<>();
        while (true) {
            String temp = scanner.nextLine();
            if (temp.equals("end")) {
                break;
            }
            String[] s = temp.split(" ");
            if (s[0].matches("[0-9]{0,100}")) {
                Student student = new Student(s[0], s[1]);
                Course course = null;
                Grade grade = new ExamScore();
                ArrayList<Float>weight=new ArrayList<>();
                if (s.length >= 5) {
                    int flag = 0;
                    for (int i = 4; i < s.length; i++) {
                        if (!s[i].matches("[0-9]{1,3}")) {
                            System.out.println("wrong format");
                            flag = 1;
                            break;
                        } else if (Integer.parseInt(s[i]) < 0 || Integer.parseInt(s[i]) > 100) {
                            System.out.println("wrong format");
                            flag = 1;
                            break;
                        }
                    }
                    if (flag == 1)
                        continue;
                }
                if (s[0].length() != 8 || s[1].length() > 10 || s[2].length() > 10 || !s[3].matches("[0-9]{1,3}") || (Integer.parseInt(s[3]) < 0 || Integer.parseInt(s[3]) > 100)) {
                    System.out.println("wrong format");
                    continue;
                }
                if (courseNameSet.contains(s[2])) {
                    for (Course tempCourse : courseUsualAverage.keySet()) {
                        if (tempCourse.name.equals(s[2])) {
                            grade.weight = scoreWeight.get(tempCourse);
                            weight=grade.weight;
                            course = tempCourse;
                            break;
                        }
                    }
                }
                if (s.length == 5 && ((Integer.parseInt(s[4]) < 0) || (Integer.parseInt(s[4]) > 100))) {
                    System.out.println("wrong format");
                    continue;
                } else if (course != null && course.mode == 2) {
                    if (s.length != grade.weight.size() + 3) {
                        System.out.println(s[0] + " " + s[1] + " " + ": access mode mismatch");
                        classTotalAverage.put(s[0].substring(0, 6), 0);
                        averageStudentScore.put(student, 0);
                        continue;
                    }
                }
                if (!courseNameSet.contains(s[2])) {
                    System.out.println(s[2] + " does not exist");
                    averageStudentScore.put(student, 0);
                    classTotalAverage.put(s[0].substring(0, 6), 0);
                    continue;
                }
                if (s.length == 4 && Objects.requireNonNull(course).mode == 1) {
                    grade = new ExamineGrade();
                    grade.weight=weight;
                    grade.finalGrade = Integer.parseInt(s[3]);
                } else if (s.length == 5 && Objects.requireNonNull(course).mode == 0) {
                    grade = new ExamScore();
                    grade.weight=weight;
                    grade.usualGrade = Integer.parseInt(s[3]);
                    grade.finalGrade = Integer.parseInt(s[4]);
                } else {
                    assert course != null;
                    if (course.mode == 2) {
                        grade = new ExperimentalScore();
                        grade.weight=weight;
                        for (int i = 3; i < s.length; i++) {
                            grade.experimentalGrades.add(Integer.parseInt(s[i]));
                        }
                    }
                }
                classTotalAverage.put(s[0].substring(0, 6), 0);
                if ((s.length == 4 && course.mode == 0) || (s.length == 5 && course.mode == 1)) {
                    System.out.println(s[0] + " " + s[1] + " " + ": access mode mismatch");
                    averageStudentScore.put(student, 0);
                    continue;
                }

                averageStudentScore.put(student, 0);
                CourseSelection courseSelection = new CourseSelection(course, student, grade);
                courseSelectionHashSet.add(courseSelection);
            }  else {
                if (!s[1].equals("实验") && s.length != 3 && s.length != 2&&s.length!=5) {
                    System.out.println("wrong format");
                    continue;
                }
                if(s[2].equals("考察")&&s.length>=5){
                    System.out.println("wrong format");
                    continue;
                }
                if ((s.length == 3) && (s[0].length() > 10 || ((!s[1].equals("必修") && !s[1].equals("选修") && !s[1].equals("实验")) || (!s[2].equals("考试") && !s[2].equals("考察") && !s[2].equals("实验"))))) {
                    System.out.println("wrong format");
                    continue;
                }
                int type = 0;
                ArrayList<Float> arrayList = new ArrayList<>();
                if (s[1].equals("必修")) type = 0;
                if (s[1].equals("选修")) type = 1;
                if (s[1].equals("实验")) type = 2;
                Course course = new Course(s[0], type);
                int mode = 0;
                if (s[2].equals("考试")) mode = 0;
                if (s[2].equals("考察")) mode = 1;
                if (s[2].equals("实验")) mode = 2;
                course.mode = mode;
                if ((course.type == 0 && course.mode == 1) || (course.mode == 2 && course.type != 2) || course.type == 2 && course.mode != 2) {
                    System.out.println(s[0] + " : course type & access mode mismatch");
                    continue;
                }
                if (s[1].equals("实验") && !s[3].matches("[4-9]")) {
                    System.out.println("wrong format");
                    continue;
                } else if (s[1].equals("实验") && Integer.parseInt(s[3]) + 4 != s.length) {
                    System.out.println(course.name + " : number of scores does not match");
                    continue;
                } else if ((s[1].equals("必修") && (int)(Float.parseFloat(s[3]) + Float.parseFloat(s[4])) != 1)) {
                    System.out.println(course.name + " : weight value error");
                    continue;
                } else if (s[1].equals("实验")) {
                    int n = Integer.parseInt(s[3]);
                    float sum = 0;
                    for (int i = 0; i < n; i++) {
                        float tempFloat = Float.parseFloat(s[i + 4]);
                        sum += tempFloat;
                        arrayList.add(tempFloat);
                    }
                    if (sum != 1) {
                        System.out.println(course.name + " : weight value error");
                        continue;
                    }
                } else if (s[2].equals("考试")) {
                    arrayList.add(Float.parseFloat(s[3]));
                    arrayList.add(Float.parseFloat(s[4]));
                }
                if(courseNameSet.contains(course.name)){
                    continue;
                }
                scoreWeight.put(course, arrayList);
                courseUsualAverage.put(course, 0);
                courseFinalAverage.put(course, 0);
                courseTotalAverage.put(course, 0);
                courseNameSet.add(s[0]);
            }
        }
        for (Student student : averageStudentScore.keySet()) {
            List<Integer> list = new ArrayList<>();
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.student.id.equals(student.id)) {
                    list.add(courseSelection.grade.getGrade());
                }
            }
            for (Integer tempScore : list) {
                averageStudentScore.replace(student, averageStudentScore.get(student) + tempScore);
            }
            if (list.size() != 0)
                averageStudentScore.replace(student, averageStudentScore.get(student) / list.size());
            if (list.size() == 0) {
                studentScorehashMap.put(student, false);
                System.out.println(student.id + " " + student.name + " " + "did not take any exams");
            } else {
                studentScorehashMap.put(student, true);
                System.out.println(student.id + " " + student.name + " " + averageStudentScore.get(student));
            }
        }
        for (Course course : courseUsualAverage.keySet()) {
            List<Integer> list = new ArrayList<>();
            List<Integer> list1 = new ArrayList<>();
            List<Integer> list2 = new ArrayList<>();
            //平时分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list.add(courseSelection.grade.usualGrade);
                }
            }
            //期末分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list1.add(courseSelection.grade.finalGrade);
                }
            }
            //综合分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list2.add(courseSelection.grade.getGrade());
                }
            }
            for (Integer tempScore : list) {
                courseUsualAverage.replace(course, courseUsualAverage.get(course) + tempScore);
            }
            for (Integer tempScore : list1) {
                courseFinalAverage.replace(course, courseFinalAverage.get(course) + tempScore);
            }
            for (Integer tempScore : list2) {
                courseTotalAverage.replace(course, courseTotalAverage.get(course) + tempScore);
            }
            if (list.size() != 0)
                courseUsualAverage.replace(course, courseUsualAverage.get(course) / list.size());
            if (list1.size() != 0)
                courseFinalAverage.replace(course, courseFinalAverage.get(course) / list1.size());
            if (list2.size() != 0)
                courseTotalAverage.replace(course, courseTotalAverage.get(course) / list2.size());
            if (list.size() == 0) {
                System.out.println(course.name + " has no grades yet");
            } else {
                System.out.println(course.name + " " + courseTotalAverage.get(course));
            }
        }
        for (String classId : classTotalAverage.keySet()) {
            int sum = 0;
            boolean flag = false;
            for (Student student : averageStudentScore.keySet()) {
                if (student.id.substring(0, 6).equals(classId)) {
                    classTotalAverage.replace(classId, classTotalAverage.get(classId) + averageStudentScore.get(student));
                    if (studentScorehashMap.get(student)) {
                        flag = true;
                        sum++;
                    }
                }
            }
            if (sum != 0)
                classTotalAverage.replace(classId, classTotalAverage.get(classId) / sum);
            if (flag) {
                System.out.println(classId + " " + classTotalAverage.get(classId));
            } else {
                System.out.println(classId + " " + "has no grades yet");
            }
        }
    }
}
类图:

变量命名不规范:代码中存在一些缩写、单个字母的变量命名,降低了码的可读性和可维护性;缺乏注释:代码中没有足够的注释来解释每个类、方法或关键代码段的功能和用途,增加了阅读和理解代码的难度

踩坑心得

  1. 搞清楚运算的方法和算法

  2. 类与类之间的关系以调用逻辑

改进建议+总结

  1. 根据需求快速了解并设计出相应类图和方法,以及类与类之间的关系。

  2. 对于算法和题目中的计算要加强理解
  3. 了解Java的基本语法,包括变量、数据类型、运算符、表达式、控制流语句等。
  4. 学习如何使用类、对象和方法,掌握面向对象编程的概念和原则。
  5. 熟悉数组的使用和常见操作,了解字符串的处理和常用方法。
  6. 学习异常处理机制,了解如何处理和抛出异常
  7. 掌握Java的核心类库,如集合框架(List、Set、Map等)和常用类(String、Math等)的使用。
  8. 学习输入输出操作,包括文件读写和控制台输入输出。
  9. 理解Java的日期和时间处理,使用Date、Calendar和新的时间API(java.time包)进行日期时间操作。
  10. 学习多线程编程,了解线程的创建、同步和通信机制
  11. 深入理解面向对象编程的概念,包括封装、继承、多态等。
  12. 学习如何设计和实现类、接口和抽象类,理解继承和实现的关系。
  13. 熟悉设计模式的常用模式,如单例模式、工厂模式、观察者模式等。
  14. 掌握异常处理的概念和使用,使用try-catch语句捕获和处理异常。
  15. 学习调试技巧,如使用断点进行代码调试,利用调试工具定位和解决问题。
  16. 学习使用Java的输入输出流,实现对文件和网络的读写操作。
  17. 熟悉文件和目录的处理,包括创建、复制、删除和遍历等操作。
  18. 了解Java开发环境的搭建和配置,如安装JDK、设置环境变量等。
  19. 学习使用常见的集成开发环境(IDE),如Eclipse、IntelliJ IDEA等,提高开发效率。
  20. 遵循Java编码规范,如命名规范、代码风格等,提高代码的可读性和可维护性。
  21. 学习使用构建工具(如Maven或Gradle)管理项目依赖和构建过程。
  22. 熟悉版本控制工具(如Git),实现代码版本管理和团队协作。

OOP 7~12次作业心得体会

OOP 7~12次作业心得体会

22201709-刘隽涛 

目录

(1)对于oop7~12次作业的理解

(2)设计与分析,测试分析性能,踩坑心得及下次改进的建议

(3)总结与看法:)

 

关于这几次作业的看法:

这7~12次题目集较第一次作业难度有进一步提高,考察抽象类、接口等。主要是围绕课程成绩统计程序进行的。第七次大作业就是成绩统计程序,第8次大作业则增加了对HashMap和多态的一个考察,第十次大作业则是增加了对Array.*部分知识点的考察。第三次写Blog,相比较上一次而言自己的经验更加的丰富了,这次blog的书写相对来说要更为轻松些。内容上题目较少,只需要分析有关课程成绩统计系统,但是说容易也并不容易,每一道题都是刺头中的刺头,这一次写博客,不仅仅是以完成任务的目的,更多的,让自己重新对那些打击过自己,折磨过自己的题目进行一次整体性的回顾。对于这次博客,我把它当作对自己过去几星期在JAVA里旅途的回望,对我付出无数心血的pta大作业的再一次审视,对我这段时间学习的一次总结。

对于OOP7~12次作业难点的理解和出错点分析

第七次作业

1.类的设计,继承与多态,接口

第八次作业

1.类的继承、多态性使用方法以及接口的应用。

第九次作业

1.hashmap和treemap的运用

第十次作业

1.增加了对Array.*部分知识点的考察。

第十一次作业

1.hashmap的检索与排序

第十二次作业

1.自定义接口ArrayIntegerStack

设计与分析

第九次作业

7-1 统计Java程序中关键词的出现次数

作者 段喜龙
单位 南昌航空大学

编写程序统计一个输入的Java源码中关键字(区分大小写)出现的次数。说明如下:

  • Java中共有53个关键字(自行百度)
  • 从键盘输入一段源码,统计这段源码中出现的关键字的数量
  • 注释中出现的关键字不用统计
  • 字符串中出现的关键字不用统计
  • 统计出的关键字及数量按照关键字升序进行排序输出
  • 未输入源码则认为输入非法

输入格式:

输入Java源码字符串,可以一行或多行,以exit行作为结束标志

输出格式:

  • 当未输入源码时,程序输出Wrong Format
  • 当没有统计数据时,输出为空
  • 当有统计数据时,关键字按照升序排列,每行输出一个关键字及数量,格式为数量\t关键字

输入样例:

在这里给出一组输入。例如:

复制代码
//Test public method
public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }
exit
复制代码

输出样例:

在这里给出相应的输出。例如:

复制代码
1    float
3    if
2    int
2    new
2    public
3    this
2    throw
复制代码

 

 

 代码:

复制代码
import java.util.*;

public class Main {
    static Scanner sc = new Scanner(System.in);
    static TreeMap<String, Integer> treeMap;

    public static void main(String[] args) {
        initializeKeywords();
        processInput();
        printKeywordCounts();
    }

    static void initializeKeywords() {
        StringBuilder stringBuilder = new StringBuilder("abstract、assert、boolean、break、byte、case、catch、char、class、continue、default、do、double、else、enum、extends、final、finally、float、for、if、implements、import、int、interface、instanceof、long、native、new、package、private、protected、public、return、short、static、strictfp、super、switch、synchronized、this、throw、throws、transient、try、void、volatile、while、goto、const、true、false、null");
        String[] keywords = stringBuilder.toString().split("\\、");
        treeMap = new TreeMap<>();
        for (String s : keywords) {
            treeMap.put(s, 0);
        }
    }

    static void processInput() {
        boolean isEmpty = true;
        int index2 = -1, index3 = -1, flag = 0; //注释2标记
        int index4 = -1; //引用标记

        while (true) {
            StringBuilder temp = new StringBuilder(sc.nextLine());
            int index1 = temp.indexOf("//");
            if (temp.toString().contains("\"")) {
                index4 = temp.indexOf("\"") + 1;
                if (index4 + 1 < temp.length()) {
                    while (temp.toString().charAt(index4) != '\"') {
                        temp.delete(index4, index4 + 1);
                        if (index4 + 1 >= temp.length())
                            break;
                    }
                }
                if (index4 + 1 < temp.length())
                    temp.delete(index4, index4 + 1);
            }
            if (temp.toString().contains("/*"))
                index2 = temp.indexOf("/*");
            if (temp.toString().contains("*/")) {
                index3 = temp.indexOf("*/");
            }
            if (index2 != 0 && index3 != 0 && !temp.toString().contains("/*")) {
                flag = 1;
            }
            if (index1 != -1) {
                temp.replace(index1, temp.length(), "");
            }
            if (index2 != -1) {
                if (index3 != -1) {
                    temp.replace(index2, index3 + 2, "");
                    index2 = -1;
                    index3 = -1;
                    flag = 0;
                } else {
                    if (flag == 0)
                        temp.replace(index2, temp.length(), "");
                    else if (flag == 1)
                        temp.replace(0, temp.length(), "");
                    continue;
                }
            }
            String[] strings = temp.toString().split("[^]a-zA-Z=\\-\\*+/\\^]+");
            for (String s : strings) {
                if (treeMap.containsKey(s)) {
                    treeMap.replace(s, treeMap.get(s) + 1);
                }
            }
            if (temp.toString().equals("exit")) {
                if (isEmpty) {
                    System.out.println("Wrong Format");
                    return;
                } else
                    break;
            }
            isEmpty = false;
        }
    }

    static void printKeywordCounts() {
        for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
            Integer integer = entry.getValue();
            if (integer != 0) {
                System.out.println(integer + "\t" + entry.getKey());
            }
        }
    }
}
复制代码

 

 圈复杂度:

 

优点:

  1. 代码逻辑清晰:代码按照一定的步骤进行初始化、处理输入和输出结果,结构较为清晰,易于理解和维护。
  2. 使用合适的数据结构:使用了 TreeMap 来存储关键字和对应的出现次数,TreeMap 可以按照关键字的自然顺序进行排序,并且具有较快的查找和插入操作。
  3. 对输入进行逐行处理:代码逐行读取输入,对每一行进行处理,这样可以有效地控制内存的使用,适用于大型输入。

缺点:

  1. 命名不规范:变量名使用了单个字母作为标识,不易于理解。建议使用更有意义的变量名来提高代码的可读性。
  2. 代码可读性较差:代码中存在大量的硬编码,缺乏注释和清晰的逻辑分隔,使得代码可读性较差,不易于理解和维护。
  3. 部分处理逻辑不完善:对于引用和注释的处理存在一些问题,可能无法正确处理所有情况。例如,引号内的代码和注释内的代码可能会对关键字统计产生干扰。
  4. 没有错误处理机制:代码没有处理异常情况的机制,例如输入错误格式的代码或者发生 I/O 异常时,没有给出相应的错误提示或处理方式。

第十次作业

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

 

 代码:

复制代码
import java.util.*;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Objects;
class Course implements Comparable<Course>{
    String name;
    int type;//0为必修,1为选修
    int mode=0;//0为考试,1为考察
    public Course(String name, int type, int mode) {
        this.name = name;
        this.type = type;
        this.mode = mode;
    }
    public Course(String name,int type){
        this.name=name;
        this.type=type;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Course course = (Course) o;
        return Objects.equals(name, course.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public int compareTo(Course o) {
        return Collator.getInstance(Locale.CHINA).compare(this.name, o.name);
    }
}
class CourseSelection {
    Course course;
    Student student;
    Score score;

    public CourseSelection(Course course, Student student, Score score) {
        this.course = course;
        this.student = student;
        this.score = score;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CourseSelection that = (CourseSelection) o;
        return Objects.equals(course, that.course) && Objects.equals(student, that.student);
    }

    @Override
    public int hashCode() {
        return Objects.hash(course, student);
    }
}
class ExamineScore extends Score{
    @Override
    Integer getScore() {
        return this.finalScore;
    }
    public ExamineScore(){
        type=1;
    }
}
class ExamScore extends Score{
    @Override
    Integer getScore() {
        return (int)( this.usualScore*0.3+this.finalScore*0.7);
    }
    public ExamScore(){
        type=0;
    }
}
abstract class Score {
    Integer finalScore=0;
    int type;
    Integer usualScore=0;
    abstract Integer getScore();
}
class Student implements Comparable<Student>{
    String id;
    String name;
    public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public int compareTo(Student s) {
        return this.id.compareTo(s.id);
    }
}
public class Main {
    public static void main(String[]args){
        Scanner scanner=new Scanner(System.in);
        HashSet<CourseSelection>courseSelectionHashSet=new HashSet<>();
        HashSet<String>courseNameSet=new HashSet<>();
        HashMap<Student,Boolean>studentScorehashMap=new HashMap<>();
        TreeMap<Student,Integer>averageStudentScore=new TreeMap<>();//综合
        TreeMap<Course,Integer>courseUsualAverage=new TreeMap<>();//平时
        TreeMap<Course,Integer>courseFinalAverage=new TreeMap<>();//期末
        TreeMap<Course,Integer>courseTotalAverage=new TreeMap<>();//结合
        TreeMap<String,Integer>classTotalAverage=new TreeMap<>();//班级
        while(true){
            String temp=scanner.nextLine();
            if(temp.equals("end")){
                break;
            }
            String[] s = temp.split(" ");
            if(s[0].matches("[0-9]{0,100}")){
                if(s.length!=5&&s.length!=4){
                    System.out.println("wrong format");
                    continue;
                }
                Student student=new Student(s[0],s[1]);
                Course course=null;
                if(s[3].contains(".")){
                    System.out.println("wrong format");
                    continue;
                }else if(s.length==5&&s[4].contains(".")){
                    System.out.println("wrong format");
                    continue;
                }
                if(s[0].length()!=8||s[1].length()>10||s[2].length()>10||Integer.parseInt(s[3])<0||Integer.parseInt(s[3])>100){
                    System.out.println("wrong format");
                    continue;
                }else if(s.length==5&&((Integer.parseInt(s[4])<0)||(Integer.parseInt(s[4])>100))){
                    System.out.println("wrong format");
                    continue;
                }
                if(courseNameSet.contains(s[2])){
                    for(Course tempCourse:courseUsualAverage.keySet()){
                        if(tempCourse.name.equals(s[2]))
                        {course=tempCourse;break;}
                    }
                }else {
                    System.out.println(s[2]+" does not exist");
                    averageStudentScore.put(student,0);
                    classTotalAverage.put(s[0].substring(0,6),0);
                    continue;
                }
                Score score=new ExamScore();
                if(s.length==4&&course.mode==1){
                    score=new ExamineScore();
                    score.finalScore=Integer.parseInt(s[3]);
                }else if(s.length==5&&course.mode==0){
                    score=new ExamScore();
                    score.usualScore=Integer.parseInt(s[3]);score.finalScore=Integer.parseInt(s[4]);
                }
                classTotalAverage.put(s[0].substring(0,6),0);
                if((s.length==4&&course.mode==0)||(s.length==5&&course.mode==1)){
                    System.out.println(s[0]+" "+s[1]+" "+": access mode mismatch");
                    averageStudentScore.put(student,0);
                    continue;
                }

                //获取每个同学,以便计算平均分
                averageStudentScore.put(student,0);
                CourseSelection courseSelection=new CourseSelection(course,student,score);
                courseSelectionHashSet.add(courseSelection);
            }else{
                if(s.length!=3&&s.length!=2){
                    System.out.println("wrong format");
                    continue;
                }
                if((s.length==3)&&(s[0].length()>10||(!s[1].equals("必修")&&!s[1].equals("选修"))||(!s[2].equals("考试")&&!s[2].equals("考察")))){
                    System.out.println("wrong format");
                    continue;
                }else if((s.length==2)&&(s[0].length()>10||!s[1].equals("必修"))){
                    System.out.println("wrong format");
                    continue;
                }
                Course course=new Course(s[0],s[1].equals("必修")?0:1);
                if(s.length==3)
                    course.mode=s[2].equals("考试")?0:1;
                if(course.type==0&&course.mode==1){
                    System.out.println(s[0]+" : course type & access mode mismatch");
                    continue;
                }
                courseUsualAverage.put(course,0);
                courseFinalAverage.put(course,0);
                courseTotalAverage.put(course,0);
                courseNameSet.add(s[0]);
            }
        }
        //平均成绩,排序
        for (Student student : averageStudentScore.keySet()) {
            List<Integer> list = new ArrayList<>();
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.student.id.equals(student.id)) {
                    list.add(courseSelection.score.getScore());
                }
            }

            for (Integer tempScore : list) {
                averageStudentScore.replace(student, averageStudentScore.get(student) + tempScore);
            }
            if(list.size()!=0)
                averageStudentScore.replace(student, averageStudentScore.get(student) / list.size());
            if (list.size() == 0) {
                studentScorehashMap.put(student,false);
                System.out.println(student.id + " " + student.name + " " + "did not take any exams");
            }else {
                studentScorehashMap.put(student,true);
                System.out.println(student.id + " " + student.name + " " + averageStudentScore.get(student));
            }
        }
        //计算每门课程的平均 平时分,期末分,综合分
        for(Course course:courseUsualAverage.keySet()){
            List<Integer>list=new ArrayList<>();
            List<Integer>list1=new ArrayList<>();
            List<Integer>list2=new ArrayList<>();
            //平时分
            for(CourseSelection courseSelection:courseSelectionHashSet){
                if(courseSelection.course.name.equals(course.name)){
                    list.add(courseSelection.score.usualScore);
                }
            }
            //期末
            for(CourseSelection courseSelection:courseSelectionHashSet){
                if(courseSelection.course.name.equals(course.name)){
                    list1.add(courseSelection.score.finalScore);
                }
            }
            //综合
            for(CourseSelection courseSelection:courseSelectionHashSet){
                if(courseSelection.course.name.equals(course.name)){
                    list2.add(courseSelection.score.getScore());
                }
            }
            for(Integer tempScore:list){
                courseUsualAverage.replace(course,courseUsualAverage.get(course)+tempScore);
            }
            for(Integer tempScore:list1){
                courseFinalAverage.replace(course,courseFinalAverage.get(course)+tempScore);
            }
            for(Integer tempScore:list2){
                courseTotalAverage.replace(course,courseTotalAverage.get(course)+tempScore);
            }
            if(list.size()!=0)
                courseUsualAverage.replace(course,courseUsualAverage.get(course)/list.size());
            if(list1.size()!=0)
                courseFinalAverage.replace(course,courseFinalAverage.get(course)/list1.size());
            if(list2.size()!=0)
                courseTotalAverage.replace(course,courseTotalAverage.get(course)/list2.size());
            if(list.size()==0){
                System.out.println(course.name+" has no grades yet");
            }else{
                if(course.mode==0)
                    System.out.println(course.name+" "+courseUsualAverage.get(course)+" "+courseFinalAverage.get(course)+" "+courseTotalAverage.get(course));
                else
                    System.out.println(course.name+" "+courseFinalAverage.get(course)+" "+courseTotalAverage.get(course));
            }
        }
        //3.计算班级的分数
        for(String classId:classTotalAverage.keySet()){
            int sum=0;//人数
            boolean flag=false;//班级是否有分数记录
            for(Student student:averageStudentScore.keySet()){
                if(student.id.substring(0,6).equals(classId)){
                    classTotalAverage.replace(classId,classTotalAverage.get(classId)+averageStudentScore.get(student));
                    if(studentScorehashMap.get(student)){
                        flag=true;
                        sum++;
                    }
                }
            }
            if(sum!=0)
                classTotalAverage.replace(classId,classTotalAverage.get(classId)/sum);
            if(flag){
                System.out.println(classId+" "+classTotalAverage.get(classId));
            }else{
                System.out.println(classId+" "+"has no grades yet");
            }
        }
    }
}
复制代码

 

类图:

 圈复杂度:

 

 

优点:

  1. 代码结构清晰,使用了类和对象来表示学生、课程、选课和成绩等概念,提高了代码的可读性和可维护性。
  2. 使用了合适的数据结构来存储数据,如HashSet、HashMap和TreeMap等,便于快速查找和操作数据。
  3. 通过重写equals()和hashCode()方法,确保对象在集合中的唯一性。
  4. 使用了面向对象的设计原则,如封装、继承和多态,提高了代码的可扩展性和重用性。

缺点:

  1. 部分代码缺乏注释,不够详细说明代码的作用和实现逻辑,给阅读代码的人理解带来一定困扰。
  2. 部分变量命名不够语义化,不利于代码的理解和维护。
  3. 部分代码逻辑比较复杂,嵌套层次较深,可读性较差,建议进行适当的重构和简化。
  4. 部分代码存在冗余和重复,可以考虑提取公共代码块或方法,提高代码的复用性和可维护性。
  5. 输入数据的格式校验不够严格,可能存在一些输入错误的情况没有进行处理和提示。

 

 

第十一次作业

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

 

 

 代码:

 

复制代码
import java.util.*;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Objects;

class Course implements Comparable<Course>{
    protected String name;
    protected int type;//0为必修,1为选修,2为实验
    protected int mode=0;//0为考试,1为考察,2为实验
    public Course(String name, int type, int mode) {
        this.name = name;
        this.type = type;
        this.mode = mode;
    }
    public Course(String name){
        this.name=name ;
    };
    public Course(String name,int type){
        this.name=name;
        this.type=type;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Course course = (Course) o;
        return Objects.equals(name, course.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public int compareTo(Course o) {
        return Collator.getInstance(Locale.CHINA).compare(this.name, o.name);
    }
}
class CourseSelection {
    protected Course course;
    protected Student student;
    protected Grade grade;

    public CourseSelection(Course course, Student student, Grade grade) {
        this.course = course;
        this.student = student;
        this.grade = grade;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CourseSelection that = (CourseSelection) o;
        return Objects.equals(course, that.course) && Objects.equals(student, that.student);
    }
    @Override
    public int hashCode() {
        return Objects.hash(course, student);
    }

}
class ExamineGrade extends Grade{
    @Override
    Integer getGrade() {
        return this.finalGrade;
    }
    public ExamineGrade(){
        type=1;
    }
}
class ExamScore extends Grade{
    @Override
    Integer getGrade() {
        return (int)( this.usualGrade*0.3+this.finalGrade*0.7);
    }
    public ExamScore(){
        type=0;
    }
}
class ExperimentalScore extends Grade{
    Integer getGrade(){
        Integer result=0;
        for(Integer integer:experimentalGrades){
            result+=integer;
        }
        return result/experimentalGrades.size();
    }
}
abstract class Grade {
    protected Integer finalGrade=0;
    protected int type;
    protected Integer usualGrade=0;
    protected ArrayList<Integer>experimentalGrades=new ArrayList<>();
    abstract Integer getGrade();
}
class Student implements Comparable<Student>{
    protected String id;
    protected String name;

    public Student() {
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public int compareTo(Student s) {
        return this.id.compareTo(s.id);
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        HashSet<CourseSelection> courseSelectionHashSet = new HashSet<>();
        HashSet<String> courseNameSet = new HashSet<>();
        HashMap<Student, Boolean> studentScorehashMap = new HashMap<>();
        TreeMap<Student,Integer>averageStudentScore=new TreeMap<>();//综合
        TreeMap<Course,Integer>courseUsualAverage=new TreeMap<>();//平时
        TreeMap<Course,Integer>courseFinalAverage=new TreeMap<>();//期末
        TreeMap<Course,Integer>courseTotalAverage=new TreeMap<>();//结合
        TreeMap<String,Integer>classTotalAverage=new TreeMap<>();//班级
        while (true) {
            String temp = scanner.nextLine();
            if (temp.equals("end")) {
                break;
            }
            String[] s = temp.split(" ");
            if (s[0].matches("[0-9]{0,100}")) {
                Student student = new Student(s[0], s[1]);
                Course course = null;
                if(s.length>=5) {
                    int flag = 0;
                    for (int i = 4; i < s.length; i++) {
                        if (!s[i].matches("[0-9]{1,3}")) {
                            System.out.println("wrong format");
                            flag = 1;
                            break;
                        } else if (Integer.parseInt(s[i]) < 0 || Integer.parseInt(s[i]) > 100) {
                            System.out.println("wrong format");
                            flag = 1;
                            break;
                        }
                    }
                    if (flag == 1)
                        continue;
                }
                if (s[0].length() != 8 || s[1].length() > 10 || s[2].length() > 10 || !s[3].matches("[0-9]{1,3}") || (Integer.parseInt(s[3]) < 0 || Integer.parseInt(s[3]) > 100)) {
                    System.out.println("wrong format");
                    continue;
                }
                if (courseNameSet.contains(s[2])) {
                    for (Course tempCourse : courseUsualAverage.keySet()) {
                        if (tempCourse.name.equals(s[2])) {
                            course = tempCourse;
                            break;
                        }
                    }
                }
                if (s.length == 5 && ((Integer.parseInt(s[4]) < 0) || (Integer.parseInt(s[4]) > 100))) {
                    System.out.println("wrong format");
                    continue;
                } else if(course!=null&&course.mode==2){
                    if (!s[3].matches("[4-9]")) {
                        System.out.println("wrong format");
                        continue;
                    }
                    if (s.length != Integer.parseInt(s[3]) + 4) {
                        System.out.println(s[0] + " " + s[1] + " " + ": access mode mismatch");
                        classTotalAverage.put(s[0].substring(0, 6), 0);
                        averageStudentScore.put(student, 0);
                        continue;
                    }
                }

                if(!courseNameSet.contains(s[2])) {
                    System.out.println(s[2] + " does not exist");
                    averageStudentScore.put(student, 0);
                    classTotalAverage.put(s[0].substring(0, 6), 0);
                    continue;
                }
                Grade grade = new ExamScore();
                if (s.length == 4 && course.mode == 1) {
                    grade = new ExamineGrade();
                    grade.finalGrade = Integer.parseInt(s[3]);
                } else if (s.length == 5 && course.mode == 0) {
                    grade = new ExamScore();
                    grade.usualGrade = Integer.parseInt(s[3]);
                    grade.finalGrade = Integer.parseInt(s[4]);
                } else if (course.mode == 2) {
                    grade = new ExperimentalScore();
                    for (int i = 4; i < s.length; i++) {
                        grade.experimentalGrades.add(Integer.parseInt(s[i]));
                    }
                }
                classTotalAverage.put(s[0].substring(0, 6), 0);
                if ((s.length == 4 && course.mode == 0) || (s.length == 5 && course.mode == 1)) {
                    System.out.println(s[0] + " " + s[1] + " " + ": access mode mismatch");
                    averageStudentScore.put(student, 0);
                    continue;
                }

                //获取每个同学,以便计算平均分
                averageStudentScore.put(student, 0);
                CourseSelection courseSelection = new CourseSelection(course, student, grade);
                courseSelectionHashSet.add(courseSelection);
            } else {
                if (s.length != 3 && s.length != 2) {
                    System.out.println("wrong format");
                    continue;
                }
                if ((s.length == 3) && (s[0].length() > 10 || ((!s[1].equals("必修") && !s[1].equals("选修") && !s[1].equals("实验")) || (!s[2].equals("考试") && !s[2].equals("考察") && !s[2].equals("实验"))))) {
                    System.out.println("wrong format");
                    continue;
                } else if ((s.length == 2) && (s[0].length() > 10 || !s[1].equals("必修"))) {
                    System.out.println("wrong format");
                    continue;
                }
                int type = 0;
                //选择
                if (s[1].equals("必修")) type = 0;
                if (s[1].equals("选修")) type = 1;
                if (s[1].equals("实验")) type = 2;
                Course course = new Course(s[0], type);
                if (s.length == 3) {
                    int mode = 0;
                    if (s[2].equals("考试")) mode = 0;
                    if (s[2].equals("考察")) mode = 1;
                    if (s[2].equals("实验")) mode = 2;
                    course.mode = mode;
                }
                if ((course.type == 0 && course.mode == 1) || (course.mode == 2 && course.type != 2) || course.type == 2 && course.mode != 2) {
                    System.out.println(s[0] + " : course type & access mode mismatch");
                    continue;
                }
                courseUsualAverage.put(course, 0);
                courseFinalAverage.put(course, 0);
                courseTotalAverage.put(course, 0);
                courseNameSet.add(s[0]);
            }
        }
        //courseSelectionHashSet.stream().map(s->s.course.name).forEach(System.out::println);
        //1.求每个同学平均成绩,排序打印
        for (Student student : averageStudentScore.keySet()) {
            List<Integer> list = new ArrayList<>();
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.student.id.equals(student.id)) {
                    list.add(courseSelection.grade.getGrade());
                }
            }
            //List<Integer> list = courseSelectionHashSet.stream().filter(s -> s.student.id.equals(student.id)).map(s -> s.grade.getGrade()).toList();
            for (Integer tempScore : list) {
                averageStudentScore.replace(student, averageStudentScore.get(student) + tempScore);
            }
            if (list.size() != 0)
                averageStudentScore.replace(student, averageStudentScore.get(student) / list.size());
            if (list.size() == 0) {
                studentScorehashMap.put(student, false);
                System.out.println(student.id + " " + student.name + " " + "did not take any exams");
            } else {
                studentScorehashMap.put(student, true);
                System.out.println(student.id + " " + student.name + " " + averageStudentScore.get(student));
            }
        }
        //每门课程的平均 平时分,期末分,综合分
        for (Course course : courseUsualAverage.keySet()) {
            List<Integer> list = new ArrayList<>();
            List<Integer> list1 = new ArrayList<>();
            List<Integer> list2 = new ArrayList<>();
            //平时分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list.add(courseSelection.grade.usualGrade);
                }
            }
            //期末分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list1.add(courseSelection.grade.finalGrade);
                }
            }
            //综合分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list2.add(courseSelection.grade.getGrade());
                }
            }
            for (Integer tempScore : list) {
                courseUsualAverage.replace(course, courseUsualAverage.get(course) + tempScore);
            }
            for (Integer tempScore : list1) {
                courseFinalAverage.replace(course, courseFinalAverage.get(course) + tempScore);
            }
            for (Integer tempScore : list2) {
                courseTotalAverage.replace(course, courseTotalAverage.get(course) + tempScore);
            }
            if (list.size() != 0)
                courseUsualAverage.replace(course, courseUsualAverage.get(course) / list.size());
            if (list1.size() != 0)
                courseFinalAverage.replace(course, courseFinalAverage.get(course) / list1.size());
            if (list2.size() != 0)
                courseTotalAverage.replace(course, courseTotalAverage.get(course) / list2.size());
            if (list.size() == 0) {
                System.out.println(course.name + " has no grades yet");
            } else {
                if (course.mode == 0)
                    System.out.println(course.name + " " + courseUsualAverage.get(course) + " " + courseFinalAverage.get(course) + " " + courseTotalAverage.get(course));
                else if(course.mode!=2)
                    System.out.println(course.name + " " + courseFinalAverage.get(course) + " " + courseTotalAverage.get(course));
                else
                    System.out.println(course.name +" "+ courseTotalAverage.get(course));
            }
        }
        //计算班级的分数
        for (String classId : classTotalAverage.keySet()) {
            int sum = 0;//人数
            boolean flag = false;//班级是否有分数记录
            for (Student student : averageStudentScore.keySet()) {
                if (student.id.substring(0, 6).equals(classId)) {
                    classTotalAverage.replace(classId, classTotalAverage.get(classId) + averageStudentScore.get(student));
                    if (studentScorehashMap.get(student)) {
                        flag = true;
                        sum++;
                    }
                }
            }
            if (sum != 0)
                classTotalAverage.replace(classId, classTotalAverage.get(classId) / sum);
            if (flag) {
                System.out.println(classId + " " + classTotalAverage.get(classId));
            } else {
                System.out.println(classId + " " + "has no grades yet");
            }
        }
    }
}
复制代码

 

 类图

 圈复杂度:

 

 

优点:

  1. 代码使用了面向对象的设计,定义了多个类来表示学生、课程和成绩等概念,使得代码结构清晰,易于理解和维护。
  2. 使用了合适的数据结构来存储数据,如HashSet、HashMap、TreeMap等,提高了数据的检索效率和存储的准确性。
  3. 实现了对学生和课程的基本操作,包括添加学生、添加课程、录入成绩等,并能计算和打印学生、课程和班级的平均分数。
  4. 使用了重写equals和hashCode方法,确保对象比较的准确性。
  5. 代码注释比较清晰,对于关键部分的功能和逻辑有所说明。

缺点:

  1. 部分代码命名不够语义化,不符合Java的命名规范,例如Grade类中的experimentalGrades应该命名为experimentalGradeList等。
  2. 部分方法和逻辑实现较为复杂,可以考虑进行重构,简化代码结构和逻辑。
  3. 输入数据格式的校验可以进一步优化,提供更详细的错误提示信息,帮助用户更好地理解输入数据的要求。
  4. 部分方法和变量的访问修饰符没有明确指定,可以进行修正,增强代码的可读性和可维护性。
  5. 缺少异常处理机制,没有对输入和运行过程中的异常情况进行处理和恢复。

 

第十二次作业

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

 

 代码:

复制代码
import java.util.*;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Objects;

class Course implements Comparable<Course>{
     String name;
     int type;//0为必修,1为选修,2为实验
     int mode=0;//0为考试,1为考察,2为实验
    public Course(String name, int type, int mode) {
        this.name = name;
        this.type = type;
        this.mode = mode;
    }
    public Course(String name){
        this.name=name ;
    };
    public Course(String name,int type){
        this.name=name;
        this.type=type;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Course course = (Course) o;
        return Objects.equals(name, course.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public int compareTo(Course o) {
        return Collator.getInstance(Locale.CHINA).compare(this.name, o.name);
    }
}
class CourseSelection {
     Course course;
     Student student;
     Grade grade;

    public CourseSelection(Course course, Student student, Grade grade) {
        this.course = course;
        this.student = student;
        this.grade = grade;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CourseSelection that = (CourseSelection) o;
        return Objects.equals(course, that.course) && Objects.equals(student, that.student);
    }
    @Override
    public int hashCode() {
        return Objects.hash(course, student);
    }

}
class ExamineGrade extends Grade{
    @Override
    Integer getGrade() {
        return this.finalGrade;
    }
    public ExamineGrade(){
        type=1;
    }
}
class ExamScore extends Grade{
    @Override
    Integer getGrade() {
        if(weight.size()!=0)
            return (int)( this.usualGrade* weight.get(0)+this.finalGrade*weight.get(1));
        return (int)( this.usualGrade* 0.3+this.finalGrade*0.7);
    }
    public ExamScore(){
        type=0;
    }
}
class ExperimentalScore extends Grade{
    Integer getGrade(){
        float result=0;
        for(int i=0;i<experimentalGrades.size();i++){
            result+=experimentalGrades.get(i)* weight.get(i);
        }
        return (int)result;
    }
}
abstract class Grade {
     Integer finalGrade=0;
     int type;
     Integer usualGrade=0;
     ArrayList<Integer>experimentalGrades=new ArrayList<>();
     ArrayList<Float>weight=new ArrayList<>();
    abstract Integer getGrade();
}
class Student implements Comparable<Student>{
     String id;
     String name;

    public Student() {
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public int compareTo(Student s) {
        return this.id.compareTo(s.id);
    }

}
public  class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        HashSet<CourseSelection> courseSelectionHashSet = new HashSet<>();
        HashSet<String> courseNameSet = new HashSet<>();
        HashMap<Student, Boolean> studentScorehashMap = new HashMap<>();
        TreeMap<Student, Integer> averageStudentScore = new TreeMap<>();
        TreeMap<Course, Integer> courseUsualAverage = new TreeMap<>();
        TreeMap<Course, Integer> courseFinalAverage = new TreeMap<>();
        TreeMap<Course, Integer> courseTotalAverage = new TreeMap<>();
        TreeMap<String, Integer> classTotalAverage = new TreeMap<>();
        TreeMap<Course, ArrayList<Float>> scoreWeight = new TreeMap<>();
        while (true) {
            String temp = scanner.nextLine();
            if (temp.equals("end")) {
                break;
            }
            String[] s = temp.split(" ");
            if (s[0].matches("[0-9]{0,100}")) {
                Student student = new Student(s[0], s[1]);
                Course course = null;
                Grade grade = new ExamScore();
                ArrayList<Float>weight=new ArrayList<>();
                if (s.length >= 5) {
                    int flag = 0;
                    for (int i = 4; i < s.length; i++) {
                        if (!s[i].matches("[0-9]{1,3}")) {
                            System.out.println("wrong format");
                            flag = 1;
                            break;
                        } else if (Integer.parseInt(s[i]) < 0 || Integer.parseInt(s[i]) > 100) {
                            System.out.println("wrong format");
                            flag = 1;
                            break;
                        }
                    }
                    if (flag == 1)
                        continue;
                }
                if (s[0].length() != 8 || s[1].length() > 10 || s[2].length() > 10 || !s[3].matches("[0-9]{1,3}") || (Integer.parseInt(s[3]) < 0 || Integer.parseInt(s[3]) > 100)) {
                    System.out.println("wrong format");
                    continue;
                }
                if (courseNameSet.contains(s[2])) {
                    for (Course tempCourse : courseUsualAverage.keySet()) {
                        if (tempCourse.name.equals(s[2])) {
                            grade.weight = scoreWeight.get(tempCourse);
                            weight=grade.weight;
                            course = tempCourse;
                            break;
                        }
                    }
                }
                if (s.length == 5 && ((Integer.parseInt(s[4]) < 0) || (Integer.parseInt(s[4]) > 100))) {
                    System.out.println("wrong format");
                    continue;
                } else if (course != null && course.mode == 2) {
                    if (s.length != grade.weight.size() + 3) {
                        System.out.println(s[0] + " " + s[1] + " " + ": access mode mismatch");
                        classTotalAverage.put(s[0].substring(0, 6), 0);
                        averageStudentScore.put(student, 0);
                        continue;
                    }
                }
                if (!courseNameSet.contains(s[2])) {
                    System.out.println(s[2] + " does not exist");
                    averageStudentScore.put(student, 0);
                    classTotalAverage.put(s[0].substring(0, 6), 0);
                    continue;
                }
                if (s.length == 4 && Objects.requireNonNull(course).mode == 1) {
                    grade = new ExamineGrade();
                    grade.weight=weight;
                    grade.finalGrade = Integer.parseInt(s[3]);
                } else if (s.length == 5 && Objects.requireNonNull(course).mode == 0) {
                    grade = new ExamScore();
                    grade.weight=weight;
                    grade.usualGrade = Integer.parseInt(s[3]);
                    grade.finalGrade = Integer.parseInt(s[4]);
                } else {
                    assert course != null;
                    if (course.mode == 2) {
                        grade = new ExperimentalScore();
                        grade.weight=weight;
                        for (int i = 3; i < s.length; i++) {
                            grade.experimentalGrades.add(Integer.parseInt(s[i]));
                        }
                    }
                }
                classTotalAverage.put(s[0].substring(0, 6), 0);
                if ((s.length == 4 && course.mode == 0) || (s.length == 5 && course.mode == 1)) {
                    System.out.println(s[0] + " " + s[1] + " " + ": access mode mismatch");
                    averageStudentScore.put(student, 0);
                    continue;
                }

                averageStudentScore.put(student, 0);
                CourseSelection courseSelection = new CourseSelection(course, student, grade);
                courseSelectionHashSet.add(courseSelection);
            }  else {
                if (!s[1].equals("实验") && s.length != 3 && s.length != 2&&s.length!=5) {
                    System.out.println("wrong format");
                    continue;
                }
                if(s[2].equals("考察")&&s.length>=5){
                    System.out.println("wrong format");
                    continue;
                }
                if ((s.length == 3) && (s[0].length() > 10 || ((!s[1].equals("必修") && !s[1].equals("选修") && !s[1].equals("实验")) || (!s[2].equals("考试") && !s[2].equals("考察") && !s[2].equals("实验"))))) {
                    System.out.println("wrong format");
                    continue;
                }
                int type = 0;
                ArrayList<Float> arrayList = new ArrayList<>();
                if (s[1].equals("必修")) type = 0;
                if (s[1].equals("选修")) type = 1;
                if (s[1].equals("实验")) type = 2;
                Course course = new Course(s[0], type);
                int mode = 0;
                if (s[2].equals("考试")) mode = 0;
                if (s[2].equals("考察")) mode = 1;
                if (s[2].equals("实验")) mode = 2;
                course.mode = mode;
                if ((course.type == 0 && course.mode == 1) || (course.mode == 2 && course.type != 2) || course.type == 2 && course.mode != 2) {
                    System.out.println(s[0] + " : course type & access mode mismatch");
                    continue;
                }
                if (s[1].equals("实验") && !s[3].matches("[4-9]")) {
                    System.out.println("wrong format");
                    continue;
                } else if (s[1].equals("实验") && Integer.parseInt(s[3]) + 4 != s.length) {
                    System.out.println(course.name + " : number of scores does not match");
                    continue;
                } else if ((s[1].equals("必修") && (int)(Float.parseFloat(s[3]) + Float.parseFloat(s[4])) != 1)) {
                    System.out.println(course.name + " : weight value error");
                    continue;
                } else if (s[1].equals("实验")) {
                    int n = Integer.parseInt(s[3]);
                    float sum = 0;
                    for (int i = 0; i < n; i++) {
                        float tempFloat = Float.parseFloat(s[i + 4]);
                        sum += tempFloat;
                        arrayList.add(tempFloat);
                    }
                    if (sum != 1) {
                        System.out.println(course.name + " : weight value error");
                        continue;
                    }
                } else if (s[2].equals("考试")) {
                    arrayList.add(Float.parseFloat(s[3]));
                    arrayList.add(Float.parseFloat(s[4]));
                }
                if(courseNameSet.contains(course.name)){
                    continue;
                }
                scoreWeight.put(course, arrayList);
                courseUsualAverage.put(course, 0);
                courseFinalAverage.put(course, 0);
                courseTotalAverage.put(course, 0);
                courseNameSet.add(s[0]);
            }
        }
        for (Student student : averageStudentScore.keySet()) {
            List<Integer> list = new ArrayList<>();
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.student.id.equals(student.id)) {
                    list.add(courseSelection.grade.getGrade());
                }
            }
            for (Integer tempScore : list) {
                averageStudentScore.replace(student, averageStudentScore.get(student) + tempScore);
            }
            if (list.size() != 0)
                averageStudentScore.replace(student, averageStudentScore.get(student) / list.size());
            if (list.size() == 0) {
                studentScorehashMap.put(student, false);
                System.out.println(student.id + " " + student.name + " " + "did not take any exams");
            } else {
                studentScorehashMap.put(student, true);
                System.out.println(student.id + " " + student.name + " " + averageStudentScore.get(student));
            }
        }
        for (Course course : courseUsualAverage.keySet()) {
            List<Integer> list = new ArrayList<>();
            List<Integer> list1 = new ArrayList<>();
            List<Integer> list2 = new ArrayList<>();
            //平时分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list.add(courseSelection.grade.usualGrade);
                }
            }
            //期末分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list1.add(courseSelection.grade.finalGrade);
                }
            }
            //综合分
            for (CourseSelection courseSelection : courseSelectionHashSet) {
                if (courseSelection.course.name.equals(course.name)) {
                    list2.add(courseSelection.grade.getGrade());
                }
            }
            for (Integer tempScore : list) {
                courseUsualAverage.replace(course, courseUsualAverage.get(course) + tempScore);
            }
            for (Integer tempScore : list1) {
                courseFinalAverage.replace(course, courseFinalAverage.get(course) + tempScore);
            }
            for (Integer tempScore : list2) {
                courseTotalAverage.replace(course, courseTotalAverage.get(course) + tempScore);
            }
            if (list.size() != 0)
                courseUsualAverage.replace(course, courseUsualAverage.get(course) / list.size());
            if (list1.size() != 0)
                courseFinalAverage.replace(course, courseFinalAverage.get(course) / list1.size());
            if (list2.size() != 0)
                courseTotalAverage.replace(course, courseTotalAverage.get(course) / list2.size());
            if (list.size() == 0) {
                System.out.println(course.name + " has no grades yet");
            } else {
                System.out.println(course.name + " " + courseTotalAverage.get(course));
            }
        }
        for (String classId : classTotalAverage.keySet()) {
            int sum = 0;
            boolean flag = false;
            for (Student student : averageStudentScore.keySet()) {
                if (student.id.substring(0, 6).equals(classId)) {
                    classTotalAverage.replace(classId, classTotalAverage.get(classId) + averageStudentScore.get(student));
                    if (studentScorehashMap.get(student)) {
                        flag = true;
                        sum++;
                    }
                }
            }
            if (sum != 0)
                classTotalAverage.replace(classId, classTotalAverage.get(classId) / sum);
            if (flag) {
                System.out.println(classId + " " + classTotalAverage.get(classId));
            } else {
                System.out.println(classId + " " + "has no grades yet");
            }
        }
    }
}
复制代码

 

类图:

 圈复杂度:

 

优点:

  1. 代码结构清晰:代码按照类的组织方式进行了划分,每个类具有清晰的职责。
  2. 使用了合适的数据结构:HashSet、HashMap、TreeMap等数据结构被恰当地用于存储和组织数据。
  3. 重写了equals()和hashCode()方法:在Course和CourseSelection类中重写了equals()和hashCode()方法,确保了正确的对象比较和哈希值生成。
  4. 采用了面向对象的设计:通过定义多个类和使用继承、抽象类等概念,实现了代码的可扩展性和复用性。

缺点:

  1. 变量命名不规范:代码中存在一些缩写、单个字母的变量命名,降低了代码的可读性和可维护性。
  2. 魔法数值硬编码:代码中出现一些硬编码的数值,缺乏可读性和可维护性,建议使用有意义的常量或枚举来替代。
  3. 缺乏注释:代码中没有足够的注释来解释每个类、方法或关键代码段的功能和用途,增加了阅读和理解代码的难度。
  4. 输入验证不完善:在部分输入验证中存在一些问题,没有覆盖所有可能的错误情况,建议进行更全面的输入验证和异常处理。

 

踩坑心得

  1. 搞清楚运算的方法和算法。

  2. 要清楚每个数据定义的范围。
  3. 类与类之间的关系以调用逻辑

改进建议

  1. 根据需求快速了解并设计出相应类图和方法,以及类与类之间的关系。

  2. 对于算法和题目中的计算要加强理解

总结

  1. 语言基础:

    • 了解Java的基本语法,包括变量、数据类型、运算符、表达式、控制流语句等。
    • 学习如何使用类、对象和方法,掌握面向对象编程的概念和原则。
    • 熟悉数组的使用和常见操作,了解字符串的处理和常用方法。
    • 学习异常处理机制,了解如何处理和抛出异常。
  2. 核心类库:

    • 掌握Java的核心类库,如集合框架(List、Set、Map等)和常用类(String、Math等)的使用。
    • 学习输入输出操作,包括文件读写和控制台输入输出。
    • 理解Java的日期和时间处理,使用Date、Calendar和新的时间API(java.time包)进行日期时间操作。
    • 学习多线程编程,了解线程的创建、同步和通信机制。
  3. 面向对象编程:

    • 深入理解面向对象编程的概念,包括封装、继承、多态等。
    • 学习如何设计和实现类、接口和抽象类,理解继承和实现的关系。
    • 熟悉设计模式的常用模式,如单例模式、工厂模式、观察者模式等。
  4. 异常处理和调试:

    • 掌握异常处理的概念和使用,使用try-catch语句捕获和处理异常。
    • 学习调试技巧,如使用断点进行代码调试,利用调试工具定位和解决问题。
  5. 输入输出和文件操作:

    • 学习使用Java的输入输出流,实现对文件和网络的读写操作。
    • 熟悉文件和目录的处理,包括创建、复制、删除和遍历等操作。
  6. Java开发工具和环境:

    • 了解Java开发环境的搭建和配置,如安装JDK、设置环境变量等。
    • 学习使用常见的集成开发环境(IDE),如Eclipse、IntelliJ IDEA等,提高开发效率。
  7. 编码规范和项目管理:

    • 遵循Java编码规范,如命名规范、代码风格等,提高代码的可读性和可维护性。
    • 学习使用构建工具(如Maven或Gradle)管理项目依赖和构建过程。
    • 熟悉版本控制工具(如Git),实现代码版本管理和团队协作。
posted @ 2023-06-27 23:58  Aomori  阅读(13)  评论(0编辑  收藏  举报