OPP课程第三阶段总结

1.前言

对于第三阶段的PTA题目集整体难度比起之前有所下降,具体体现在代码量和逻辑思维上,但是对于知识点的考察要求依然严格,主要考察了Comparable的接口的使用,正则表达式的灵活运用,TreeMap的运用,HashMap的运用以及对于大量对象信息的匹配和储存。我这篇Blog也会对于我上述的考察知识点给出对应的题目及其分析。


2.设计与分析

OPP训练集08

7-2 图形卡片分组游戏

题目如下:

 

分析:本题主要要使每个图形类实现Comparable接口,并在对应类中重写compareTo的方法,然后创建对应类的ArrayList来储存对应类型图形的数据,根据输入的数字来储存到不同的ArrayList中,最后对对应的ArrayList调用Collections.sort()方法来进行排序,再使用强化for输出数据。

代码如下

import java.util.*;
public class Main {
   public static Scanner input = new Scanner(System.in);
   public static void main(String[] args){
       ArrayList<Integer> list = new ArrayList<Integer>();
       int num = input.nextInt();
       if(list.size()==0&&num==0){
           System.out.println("Wrong Format");
           return ;
      }
       while(num != 0){
           if(num < 0 || num > 4){
               System.out.println("Wrong Format");
               System.exit(0);
          }
           list.add(num);
           num = input.nextInt();
      }
       DealCardList dealCardList = new DealCardList(list);
       if(!dealCardList.validate()){
           System.out.println("Wrong Format");
           System.exit(0);

      }
       dealCardList.showResult();
       input.close();
  }
}
abstract class Shape{
   private String shapeName;

   public Shape(String shapeName) {
       this.shapeName = shapeName;
  }

   public Shape() {
  }

   public String getShapeName() {
       return shapeName;
  }

   public void setShapeName(String shapeName) {
       this.shapeName = shapeName;
  }
   abstract public double getArea();
   abstract public boolean validate();
    public String toString(){return shapeName;}
}
class Circle extends Shape implements Comparable<Circle>{
   private double radius;

   public Circle(double radius) {
       super("Circle");
       this.radius = radius;
  }

   public Circle() {
  }
   public double getRadius() {
       return radius;
  }

   public void setRadius(double radius) {
       this.radius = radius;
  }
   public double getArea(){
       return Math.PI*radius*radius;
  }

   @Override
   public boolean validate() {
       if(radius<0)
       return false;
       return true;
  }
   public int compareTo(Circle card){
       if(this.getArea()>card.getArea())return -1;
       else if(this.getArea()==card.getArea())return 0;
       else return 1;
  }
}
class Trapezoid extends Shape implements Comparable<Trapezoid>{
   private double topSide;
   private double bottomSide;
   private double height;

   public Trapezoid(double topSide, double bottomSide, double height) {
       super("Trapezoid");
       this.topSide = topSide;
       this.bottomSide = bottomSide;
       this.height = height;
  }

   public Trapezoid() {
  }

   public double getArea(){
       return (topSide+bottomSide)*height/2.0;
  }
   public boolean validate(){
       if(topSide<0||bottomSide<0||height<0)
           return false;
       return true;
  }
   public int compareTo(Trapezoid card){
       if(this.getArea()>card.getArea())return -1;
       else if(this.getArea()==card.getArea())return 0;
       else return 1;
  }
}
class Rectangle extends Shape implements Comparable<Rectangle>{
   private double width;
   private double length;

   public Rectangle(double width, double length) {
       super("Rectangle");
       this.width = width;
       this.length = length;
  }

   public Rectangle() {
  }

   public double getWidth() {
       return width;
  }

   public void setWidth(double width) {
       this.width = width;
  }

   public double getLength() {
       return length;
  }

   public void setLength(double length) {
       this.length = length;
  }
   public double getArea(){
       return width* length;
  }
   public boolean validate(){
       if(length<0||width<0)
           return false;
       return true;
  }
   public int compareTo(Rectangle card){
       if(this.getArea()>card.getArea())return -1;
       else if(this.getArea()==card.getArea())return 0;
       else return 1;
  }
}
class Triangle extends Shape implements Comparable<Triangle>{
   private double side1;
   private double side2;
   private double side3;

   public Triangle(double side1, double side2, double side3) {
       super("Triangle");
       this.side1 = side1;
       this.side2 = side2;
       this.side3 = side3;
  }

   public Triangle() {
  }

   public double getArea(){
       double p = (side1+side2+side3)/2.0;
       return Math.sqrt(p*(p-side2)*(p-side1)*(p-side3));
  }
   public boolean validate(){
       if(side1<0||side2<0||side3<0||side1+side2<=side3||side1+side3<=side2||side2+side3<=side1)
           return false;
       return true;
  }
   public int compareTo(Triangle card){
       if(this.getArea()>card.getArea())return -1;
       else if(this.getArea()==card.getArea())return 0;
       else return 1;
  }
}
   class Card implements Comparable<Card>{
       private Shape shape;

       public Card(Shape shape) {
           this.shape = shape;
      }

       public Card() {
      }

       public Shape getShape() {
           return shape;
      }

       public void setShape(Shape shape) {
           this.shape = shape;
      }
       public int compareTo(Card card){
           if(this.shape.getArea()>card.shape.getArea())return -1;
           else if(this.shape.getArea()==card.shape.getArea())return 0;
           else return 1;
      }
}
class DealCardList{
   ArrayList<Card> cardList = new ArrayList<Card>();
   ArrayList<Circle> circleList = new ArrayList<Circle>();
   ArrayList<Trapezoid> trapezoidsList = new ArrayList<Trapezoid>();
   ArrayList<Triangle> trianglesList = new ArrayList<Triangle>();

   ArrayList<Rectangle> rectanglesList = new ArrayList<Rectangle>();

   public DealCardList(ArrayList<Integer> list) {
       for(int i:list) {
           if(i==1) {
               Circle circle = new Circle(Main.input.nextDouble());
               Card card = new Card(circle);
               cardList.add(card);
                   circleList.add(circle);
          }
           else if(i==2) {
               Rectangle rectangle = new Rectangle(Main.input.nextDouble(),Main.input.nextDouble());
               Card card = new Card(rectangle);
               cardList.add(card);
               rectanglesList.add(rectangle);
          }
           else if(i==3) {
               Triangle triangle = new Triangle(Main.input.nextDouble(),Main.input.nextDouble(),Main.input.nextDouble());
               Card card = new Card(triangle);
               cardList.add(card);
               trianglesList.add(triangle);
          }else if(i==4) {
               Trapezoid trapezoid = new Trapezoid(Main.input.nextDouble(),Main.input.nextDouble(),Main.input.nextDouble());
               Card card = new Card(trapezoid);
               cardList.add(card);
               trapezoidsList.add(trapezoid);
          }
      }
  }
   public DealCardList() {
  }
   public boolean validate(){
       for(int i=0;i<cardList.size();i++){
           if(!cardList.get(i).getShape().validate())
               return false;

      } return true;
  }
   public double maxArea(){
       double sum1=0,sum2=0,sum3=0,sum4=0;
       for(Circle circle:circleList){
           sum1+=circle.getArea();
      }
       for(Rectangle rectangle:rectanglesList){
           sum2+=rectangle.getArea();
      }
       for(Triangle triangle:trianglesList){
           sum3+=triangle.getArea();
      }
       for(Trapezoid trapezoid:trapezoidsList){
           sum4+=trapezoid.getArea();
      }
       return Math.max(sum1,Math.max(sum2,Math.max(sum3,sum4)));
  }
   public void showResult() {
       System.out.println("The original list:");
       System.out.print("[");
       for(Card card:cardList) {
           System.out.print(card.getShape()+":"+String.format("%.2f",card.getShape().getArea())+" ");
      }
       System.out.print("]");
       System.out.println("\nThe Separated List:");
       System.out.print("[");
       for(Circle circle:circleList) {
           System.out.print("Circle:"+String.format("%.2f",circle.getArea())+" ");
      }
       System.out.print("]");
       System.out.print("[");
       for(Rectangle rectangle:rectanglesList) {
           System.out.print("Rectangle:"+String.format("%.2f",rectangle.getArea())+" ");
      }
       System.out.print("]");
       System.out.print("[");
       for(Triangle triangle:trianglesList) {
           System.out.print("Triangle:"+String.format("%.2f",triangle.getArea())+" ");
      }
       System.out.print("]");
       System.out.print("[");
       for(Trapezoid trapezoid:trapezoidsList) {
           System.out.print("Trapezoid:"+String.format("%.2f",trapezoid.getArea())+" ");
      }
       System.out.print("]");
       System.out.println("\nThe Separated sorted List:");
       Collections.sort(trianglesList);
       Collections.sort(circleList);
       Collections.sort(trapezoidsList);
       Collections.sort(rectanglesList);
       System.out.print("[");
       for(Circle circle:circleList) {
           System.out.print("Circle:"+String.format("%.2f",circle.getArea())+" ");
      }
       System.out.print("]");
       System.out.print("[");
       for(Rectangle rectangle:rectanglesList) {
           System.out.print("Rectangle:"+String.format("%.2f",rectangle.getArea())+" ");
      }
       System.out.print("]");
       System.out.print("[");
       for(Triangle triangle:trianglesList) {
           System.out.print("Triangle:"+String.format("%.2f",triangle.getArea())+" ");
      }
       System.out.print("]");
       System.out.print("[");
       for(Trapezoid trapezoid:trapezoidsList) {
           System.out.print("Trapezoid:"+String.format("%.2f",trapezoid.getArea())+" ");
      }
       System.out.print("]");
       System.out.println("\nThe max area:"+String.format("%.2f",maxArea()));
  }
}

心得

对comparable的接口的使用,重写compareTo方法,Collections.sort()的排序都有了更高的熟练度,也对数据分类储存有了进一步的理解。


OPP训练集09

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

题目如下

 

分析:首先需要用一个字符串keywords去储存所有的关键字,然后用StringBuilder这个可变字符串数组去储存输入数据,再对数据进行分别的正则表达式处理来获得有效部分,如:

  1. Codes = Codes.replaceAll("//[\\s\\S]*?\\n", "");

这行代码使用正则表达式替换操作,删除单行注释(// ...)及其之后的换行符。

  1. Codes = Codes.replaceAll("^\\s*\\n\n", "");

这行代码使用正则表达式替换操作,删除连续的空行。

  1. Codes = Codes.replaceAll("[\"].+[\"]", "");

这行代码使用正则表达式替换操作,删除双引号包围的字符串。

  1. Codes = Codes.replaceAll("=[a-z]{1,5}", "");

这行代码使用正则表达式替换操作,删除等号后面跟着1到5个小写字母的内容。

  1. Codes = Codes.replaceAll(" +", " ");

这行代码使用正则表达式替换操作,将连续的多个空格替换为单个空格。

  1. String[] Code = Codes.split("[\\W]");

这行代码使用正则表达式分割操作,将字符串 Codes 按照非单词字符进行分割,返回一个字符串数组。这里的非单词字符包括除字母、数字和下划线以外的其他字符。

最终,代码返回字符串数组 Code,其中包含了经过处理的代码分割后的单词或短语。

最后用TreeMap储存可以对关键词进行排序。

代码如下

import java.util.*;

public class Main {
   public static void main(String[] args) {
       // 关键字列表
       String[] keywords = {"abstract", "assert", "boolean",
               "break", "byte", "case", "catch", "char", "class", "const",
               "continue", "default", "do", "double", "else", "enum",
               "extends", "for", "final", "finally", "float", "goto",
               "if", "implements", "import", "instanceof", "int",
               "interface", "long", "native", "new", "package", "private",
               "protected", "public", "return", "short", "static",
               "strictfp", "super", "switch", "synchronized", "this",
               "throw", "throws", "transient", "try", "void", "volatile",
               "while", "true", "false", "null"};

       // 读取输入源码
       Scanner sc = new Scanner(System.in);
       StringBuilder sourceCode = new StringBuilder();
       String line = null;
       while (sc.hasNextLine()) {
           line = sc.nextLine();
           if (line.equals("exit"))
               break;
           sourceCode.append(line);
           sourceCode.append("\n");
      }
       // 检查输入源码是否为空
       if (sourceCode.toString().trim().isEmpty()) {
           System.out.println("Wrong Format");
           return;
      }

       // 统计关键字出现次数
       Map<String, Integer> keywordCount = new TreeMap<>();
       for (String keyword : keywords) {
           keywordCount.put(keyword, 0);
      }
       String sourceCodes = sourceCode.toString();
       String Codes = sourceCodes.replaceAll("/\\*{1,2}[\\s\\S]*?\\*/\n", "");
       Codes = Codes.replaceAll("//[\\s\\S]*?\\n", "");
       Codes = Codes.replaceAll("^\\s*\\n\n", "");

       Codes = Codes.replaceAll("[\"].+[\"]", "");
       Codes = Codes.replaceAll("=[a-z]{1,5}", "");
       Codes = Codes.replaceAll(" +", " ");
       String[] Code = Codes.split("[\\W]");
       ArrayList<String> codeList = new ArrayList<>(Arrays.asList(Code));
       ArrayList<String> keywordList = new ArrayList<>(Arrays.asList(keywords));

       for(String list:codeList){
           if(keywordList.contains(list)){
               for(String keyword:keywordList){
                   if(keyword.equals(list)){
                       keywordCount.put(list,keywordCount.get(list)+1);
                       break;
                  }
              }
          }
      }

       for (Map.Entry<String, Integer> entry : keywordCount.entrySet()) {
           if (entry.getValue() > 0) {
               System.out.println(entry.getValue() + "\t" + entry.getKey());
          }
      }


  }
}

心得

对正则表达式的灵活使用有了更强的理解,学会了TreeMap的遍历,储存等操作,知道了该如何去去除无用数据保留有效数据的逻辑。

OPP训练集11

7-2 容器-HashMap-排序

题目如下

 

分析

创建Student的类和存储学生信息的 HashMap,尽管map只能有键和值两个数据,而学生有三个数据,但我们可以比如一个值里面储存两个学生数据,然后对键进行排序的思路,由于本题还要求是逆序,所以我们要学习使用Collections.sort(list, Collections.reverseOrder())来反向排序,最后用强化for去遍历对象的数据来输出。

代码如下

import java.util.*;

public class Main {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       Map<String, String> map = new HashMap<>(); // 存储学生信息的 HashMap
       String line=null;
       while(true){
           line =sc.nextLine();
           if (line.equals("end")) {
               break;
          }
           String input[]=line.split(" ");
           //Student student=new Student(input[0],input[1],Integer.parseInt(input[2]));
           map.put(input[0],input[1] + " " + input[2]);
      }
       List<String> list = new ArrayList<>(map.keySet()); // 将学号转换为列表
       Collections.sort(list, Collections.reverseOrder()); // 对学号进行排序
       for(String lists:list){
           String value=map.get(lists);
               System.out.println(lists+" "+value);

      }
  }

}
class Student{
   private String num;
   private String name;
   private int score;

   public Student(String num, String name, int score) {
       this.num = num;
       this.name = name;
       this.score = score;
  }

   public Student() {
  }

   public String getNum() {
       return num;
  }

   public void setNum(String num) {
       this.num = num;
  }

   public String getName() {
       return name;
  }

   public void setName(String name) {
       this.name = name;
  }

   public int getScore() {
       return score;
  }

   public void setScore(int score) {
       this.score = score;
  }
}

心得

我学会了如何用只有key和value的hashmap去储存三个数据的信息,明白了怎么去根据key去排序,以及反向排序,最后再用强化for去输出数据。


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

题目如下

 

分析

本题基于程序1的迭代,增加了一个实验课的情况。该题的难点在于正则表达式对于数据的处理,以及如何判断实验课的实验次数和输入的实验成绩数不匹配的情况。

代码如下

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.text.Collator;
import java.util.Comparator;

public class Main {
   public static void main(String[] args) {
       Scanner sc= new Scanner (System.in);
       //初始化一个Work类,开始读入数据
       Work work = new Work();
       //读入数据
       String message = sc.nextLine();
       while (!message.equals("end")){   //当message不是end的时候
           work.manage(message);   //在Work类里面处理类
           message = sc.nextLine();  //读入下一行
      }
       //输出学生
       work.show_Student();
       //输出课程
       work.show_Course();
       //输出班级
       work.show_Classroom();
  }
}
class Work {
   ArrayList<Student> listStudent = new ArrayList<>();   //学生表
   ArrayList<Classroom> listClassroom = new ArrayList<>();    //班级表
   ArrayList<Course> listCourse = new ArrayList<>();   //课程表
   ArrayList<Message_Box> listMessage_Box = new ArrayList<>();   //选课记录表
   InputMatching matching = new InputMatching();
   public void manage(String message) {
       String Line[] = message.split(" " );
       switch (matching.matchingInput(message)) {
           case 1 : {   //输入的是课程
               Course course = new Course(Line[0],Line[1],Line[2]);
               if (Error_Course((course))){
                   Message_Box messageBox = new Message_Box(null,course,null);
                   if (Exist_Course(course))
                       listCourse.add(course);
              }
               else {
                   System.out.println(course.getName() + " : course type & access mode mismatch");
              }
               break;
          }
           case 2: {   //输入的是学生
               Course course = find_CourseByName(Line[2]);
               Student student = new Student(Integer.parseInt(Line[0]),Line[1]);
               Classroom classroom = new Classroom(student.getId()/100);
               if (Exist_Student(student))
                   listStudent.add(student);
               if (Exist_Classroom(classroom))
                   listClassroom.add(classroom);
               if (course!= null) {
                   if (Line.length == 4) {
                       if (course.getGrade_Way().equals("考察")){
                           Grade grade = new Grade_Exam(Line[3]);
                           Message_Box messageBox = new Message_Box(student,course,grade);
                           if (Exist_Message(messageBox))
                               listMessage_Box.add(messageBox);
                      } else {
                           System.out.println(Line[0] + " " + Line[1] + " : " +"access mode mismatch");
                      }
                  } else {
                       if (course.getGrade_Way().equals("考试") && Line.length == 5) {
                           Grade grade = new Grade_daily(Line[3],Line[4]);
                           Message_Box messageBox = new Message_Box(student,course,grade);
                           if (Exist_Message(messageBox))
                               listMessage_Box.add(messageBox);
                      }
                       else if (course.getGrade_Way().equals("实验") && Line.length-4 == Integer.parseInt(Line[3])) {
                           Grade grade = new Grade_Lab(Line);
                           Message_Box messageBox = new Message_Box(student,course,grade);
                           if (Exist_Message(messageBox))
                               listMessage_Box.add(messageBox);
                      }
                       else {
                           System.out.println(Line[0] + " " + Line[1] + " : " +"access mode mismatch");
                      }
                  }
              }
               else {
                   System.out.println(Line[2] + " " + "does not exist");
              }
               break;
          }
           default: {
               System.out.println("wrong format");
          }
      }
  }

   private boolean Exist_Message(Message_Box messageBox) {
       for(Message_Box messageBox1 : listMessage_Box){
           if ((messageBox.student.getId() == messageBox1.student.getId()) && (messageBox1.course.getName().equals(messageBox.course.getName()))){
               return false;
          }
      }
       return true;
  }
   private boolean Exist_Classroom(Classroom classroom) {
       for(Classroom classroom1 : listClassroom){
           if (classroom1.getClass_ID()==classroom.getClass_ID()){
               return false;
          }
      }
       return true;
  }
   private boolean Exist_Student(Student student) {
       for (Student student1 : listStudent){
           if (student1.getId() == student.getId()){
               return false;
          }
      }
       return true;
  }
   private boolean Exist_Course(Course course) {
       for (Course course1 : listCourse){
           if (course1.getName().equals(course.getName())){
               return false;
          }
      }
       return true;
  }
   private Course find_CourseByName(String name) {
       for (int i = 0 ; i < listCourse.size() ; i++) {
           if (listCourse.get(i).getName().equals((name))){
               return listCourse.get(i);
          }
      }
       return null;
  }
   private boolean Error_Course(Course course) {
       if (course.getCourse_Message().equals("必修") && course.getGrade_Way().equals("考察")){
           return false;
      }
       else if ((course.getCourse_Message().equals("实验") && !course.getGrade_Way().equals("实验")) || (!course.getCourse_Message().equals("实验") && course.getGrade_Way().equals("实验"))){
           return false;
      }
       else {
           return true;
      }
  }
   public void show_Student() {
       //按学号排序
       Collections.sort(listStudent);
       for (int i = 0 ; i < listStudent.size() ; i++) {   //这里的循环是用来遍历每一位学生
           Student stu = listStudent.get(i);
           //从总课表listChooseCourse中获取该学生的选课记录集合
           ArrayList<Message_Box> stuCourseSelects = getStudentSelects(stu.getId());
           if (stuCourseSelects.size() != 0) {
               System.out.println(stu.getId() + " " + stu.getName() + " " + getAvgTotalScore(stuCourseSelects));
          }  else {
               System.out.println(stu.getId() + " " + stu.getName() + " " + "did not take any exams");
          }
      }
  }
   //获得该学生选课记录的情况下返回该学生的总成绩
   private int getAvgTotalScore(ArrayList<Message_Box> stuCourseSelects) {
       int total = 0;
       for (Message_Box messageBox : stuCourseSelects) {
           total += messageBox.grade.get_TotalGrade();
      }
       return (int)(1.0*total/stuCourseSelects.size());
  }
   //通过学生的Id查找选课记录表,返回该学生的选课记录
   private ArrayList<Message_Box> getStudentSelects(int id) {
       ArrayList<Message_Box> student_Message = new ArrayList<>();
       for (Message_Box messageBox : listMessage_Box) {
           if (messageBox.student.getId() == id) {
               student_Message.add(messageBox);
          }
      }
       return student_Message;
  }
   public void show_Course() {
       //按中文拼音进行排序
       Collections.sort(listCourse);
       for (int i = 0 ; i < listCourse.size() ; i++) {   //这里的循环是用来遍历每一位课程
           Course course = listCourse.get(i);
           //从总选课记录listCourse中获取该课程的学生信息集合
           ArrayList<Message_Box> courseStudentSelects = getcourseStudentSelects(course.getName());
           if (courseStudentSelects.size() != 0) {
               if (course.getGrade_Way().equals("考察")) {
                   System.out.println(course.getName() + " " + getAvgExamScore(courseStudentSelects) + " " + getAvgTotalCourse(courseStudentSelects));
              }
               else if (course.getGrade_Way().equals("考试")){
                   System.out.println(course.getName() + " " + getAvgDailyScore(courseStudentSelects) + " " + getAvgExamScore(courseStudentSelects) + " " + getAvgTotalCourse(courseStudentSelects));
              }
               else if (course.getGrade_Way().equals("实验")) {
                   System.out.println(course.getName() + " " + getAvgTotalCourse(courseStudentSelects));
              }
          }
           else {
               System.out.println(course.getName() + " " + "has no grades yet");
          }
      }
  }
   private int getAvgTotalCourse(ArrayList<Message_Box> courseStudentSelects) {
       int total = 0;
       for (Message_Box messageBox : courseStudentSelects) {
           total += messageBox.grade.get_TotalGrade();
      }
       return (int)(1.0*total/courseStudentSelects.size());
  }
   private int getAvgDailyScore(ArrayList<Message_Box> courseStudentSelects) {
       int total = 0;
       for (Message_Box messageBox : courseStudentSelects) {
           total += ((Grade_daily)messageBox.grade).get_DailyGrade();
      }
       return (int)(1.0*total/courseStudentSelects.size());
  }
   private int getAvgExamScore(ArrayList<Message_Box> courseStudentSelects) {
       int total = 0;
       for (Message_Box messageBox : courseStudentSelects) {
           total += messageBox.grade.get_ExamGrade();
      }
       return (int)(1.0*total/courseStudentSelects.size());
  }
   private ArrayList<Message_Box> getcourseStudentSelects(String name) {
       ArrayList<Message_Box> course_Message = new ArrayList<>();
       for (Message_Box messageBox : listMessage_Box) {
           if (messageBox.course.getName().equals(name)) {
               course_Message.add(messageBox);
          }
      }
       return course_Message;
  }
   public void show_Classroom() {
       Collections.sort(listClassroom);
       for (int i = 0 ; i < listClassroom.size() ; i++) {
           Classroom classroom = listClassroom.get(i);
           ArrayList<Message_Box> classroomSelects = getClassSelects(classroom.getClass_ID());
           if (classroomSelects.size() != 0) {
               System.out.println(classroom.getClass_ID() + " " + getAvgTotalClassScore(classroomSelects));
          }  else {
               System.out.println(classroom.getClass_ID() + " " + "has no grades yet");
          }
      }
  }
   private int getAvgTotalClassScore(ArrayList<Message_Box> classroomSelects) {
       int total = 0;
       for (Message_Box messageBox : classroomSelects) {
           total += messageBox.grade.get_TotalGrade();
      }
       return (int)(1.0*total/classroomSelects.size());
  }
   private ArrayList<Message_Box> getClassSelects(int classId) {
       ArrayList<Message_Box> class_Message = new ArrayList<>();
       for (Message_Box messageBox : listMessage_Box) {
           if (messageBox.student.getId()/100 == classId) {
               class_Message.add(messageBox);
          }
      }
       return class_Message;
  }
   class InputMatching {
       String Lab_Times_Matching = "[4-9]{1}";  //1个0-9的数字
       String stuNumMatching = "[0-9]{8}";//8个0-9的数字
       String stuNameMatching = "\\S{1,10}";//1到10个非空格(TAB)字符
       String scoreMatching = "([1-9]?[0-9]|100)";
       String courseNameMatching = "\\S{1,10}";//1到10个非空格(TAB)字符
       String courseTypeMatching = "(选修|必修|实验)";
       String checkCourseTypeMatching = "(考试|考察|实验)";
       //courseInput用于定义课程信息模式(正则表达式)   /*这里的正则表达式考虑到了长度为二的情况吗? 这里的测试测试点似乎并不考虑这给error问题*/
       String courseInput = courseNameMatching + " " + courseTypeMatching + " " + checkCourseTypeMatching;
       //scoreInput用于定义成绩信息模式(正则表达式)
       String scoreInput = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " +
               scoreMatching + "(scoreMatching)?";
       String scoreInput_2 = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " +
               scoreMatching + " " + scoreMatching;
       String lab_Input_0 = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " + Lab_Times_Matching;
       public int matchingInput(String s) {
           String[] input = s.split(" ");
           String Lab_up = "";
           if (input.length >= 5) {
               Lab_up = input[0] + " " + input[1] + " " + input[2] + " " + input[3];
          }
           if (matchingCourse(s)) {
               return 1;
          }
           if (matchingScore(s) || s.matches(scoreInput_2)) {
               return 2;
          }
           if (matching_Lab(Lab_up)){   //输入符合实验的前提条件
               int number = Integer.parseInt(input[3]);
               for (int i = 4 ; i < input.length ; i++) {   //查看后续条件是否符合
                   if (!input[i].matches(scoreMatching)) {   //如果找到一个不符合的
                       return 0;
                  }
              }
               return 2;
          }
           return 0;
      }
       private boolean matchingCourse(String s) {

           return s.matches(courseInput);
      }
       private boolean matchingScore(String s) {
           //System.out.println(match);
           return s.matches(scoreInput);
      }
       private boolean matching_Lab (String s) {
           return s.matches(lab_Input_0);
      }
  }
}
class Student implements Comparable<Student>{
   private int id;
   private String name;
   Student(int id , String name) {
       this.name = name;
       this.id = id;
  }
   @Override
   //学号排序
   public int compareTo(Student o) {
       return (this.id - o.getId());
  }
   public int getId() {
       return id;
  }
   public String getName() {
       return name;
  }
}
class Course implements Comparable<Course>{
   Course(String name , String Course_Message , String Grade_Way) {
       this.name = name;
       this.Course_Message = Course_Message;
       this.Grade_Way = Grade_Way;
  }
   private String name;
   private String Course_Message;
   private String Grade_Way;
   @Override
   public int compareTo(Course o) {
       Comparator<Object> compare = Collator.getInstance(java.util.Locale.CHINA);
       return compare.compare(name,o.getName());
  }
   public String getName() {
       return name;
  }
   public String getGrade_Way() {
       return Grade_Way;
  }
   public String getCourse_Message() {
       return Course_Message;
  }
}
class Classroom implements Comparable<Classroom>{
   Classroom(int Id) {
       this.class_ID = Id;
  }
   private int class_ID;
   @Override
   public int compareTo(Classroom o) {
       return this.class_ID - o.getClass_ID();
  }
   public int getClass_ID() {
       return class_ID;
  }
}
abstract class Grade {
   private int Exam;
   public abstract int get_TotalGrade();
   public abstract int get_ExamGrade();
   public void setExam(int exam) {
       this.Exam = exam;
  }
   public int getExam() {
       return Exam;
  }
}
class Grade_daily extends Grade {
   Grade_daily(String Daily , String Exam) {
       setDaily(Integer.parseInt(Daily));
       setExam(Integer.parseInt(Exam));
  }
   private int Daily;
   public int get_TotalGrade() {
       return (int)(this.getDaily()*0.3 + this.getExam()*0.7);
  }
   public int get_DailyGrade() {
       return this.getDaily();
  }
   public int get_ExamGrade() {
       return this.getExam();
  }
   public void setDaily(int daily) {
       Daily = daily;
  }
   public int getDaily() {
       return Daily;
  }
}
class Grade_Exam extends Grade{
   Grade_Exam(String Exam) {
       setExam(Integer.parseInt(Exam));
  }
   public int get_TotalGrade() {
       return (int)(this.getExam()*1.0);
  }

   public int get_ExamGrade() {
       return this.getExam();
  }
}
class Grade_Lab extends Grade{
   private int Laboratory = 0;
   private int times;
   Grade_Lab(String[] Inputs) {
       times=Integer.parseInt(Inputs[3]);
       for (int i = 4 ; i < Inputs.length; i++) {
           Laboratory += Integer.parseInt(Inputs[i]);
      }
  }
   @Override
   public int get_TotalGrade() {
       return (int)(1.0*Laboratory/times);
  }

   @Override
   public int get_ExamGrade() {
       return 0;
  }
}
class Message_Box {
   Student student;
   Course course;
   Grade grade;
   Message_Box(Student student , Course course , Grade grade) {
       this.student = student;
       this.course = course;
       this.grade = grade;
  }
}

心得

本题主要练习了对于大量对象信息的匹配,排序,储存以及输入,其中对数据进行了大量的处理与分析,对逻辑思维能力有了很大的锻炼。

3.踩坑心得

易踩坑点一:

7-1 统计Java程序中关键词的出现次数:该开始用正则表达式去去除无效数据的顺序有问题,导致无法保留完整的有效数据。

 

解决方法:与同学交流,并且仔细分析测试点提示。


易踩坑点二:

7-2 容器-HashMap-排序:我刚开始在看到题目要求要用hashmap去储存时,不知道怎么用只有key和value的hashmap去储存,也不知道该怎么进行反向的排序。

解决方法:仔细查阅资料,理解储存的方式,而且找到了Collections.sort(list, Collections.reverseOrder())可以反向排序。


4.改进建议

改进见解

在课程成绩程序的一系列题目中,对于代码的复用率不高,导致代码冗长麻烦,要将复用多的代码,学会打包成方法的形式来进行调用,正确代码的复用度,还有些正则表达式的运用不够精炼,可以进一步的改进更加精炼。


5.总结

收获:

  • 学会了comparable的接口的使用,重写compareTo方法,Collections.sort()的排序

  • 掌握了正则表达式的更多元的灵活使用

  • 学习了TreeMap,HashMap的底层原理以及更多的运用

  • 对大量的数据的分类,储存,排序,遍历等有了更清晰的思路

对Java程序设计课的感受与建议:

  • 关于教学理念(OBE):可以让学生不止把学到的知识应用于题目理论中,可以尝试着在实践中将知识应用,会让知识的理解和使用更加的透彻

  • 关于教学方法(边讲边练):要坚持边讲边练的教学方法,空洞的知识需要不断的练习去支持。

  • 关于教学组织(线上线下混合式教学):赞同线上线下混合式教学,但是其实可以不局限于学习通的线上教学,可以开拓线上学习的领域,让学生自主的选择适合自己的线上学习资源以及学习模式,可以同时开展线上以及线下的答疑,对知识点会有更好的巩固效果。

  • 关于教学过程(PTA题目集驱动):PTA可以多多层次多难度的出题,同时建议给出相应的题解以及评论区来对一道题大家分享不同的方法与见解。

  • 关于教学模式(BOPPPS):可以多进行一些相关知识的实践,能不能定期完成一个相关知识的小项目来达成对此知识的真实应用。

  •  
![image-20230624172906420](C:/Users/%E8%8B%8F%E9%92%B0%E9%95%94/AppData/Roaming/Typora/typora-user-images/image-20230624172906420.png)
posted @ 2023-06-24 22:18  添砖_java~  阅读(92)  评论(0)    收藏  举报