首页 > 其他分享 >题目集6~8总结

题目集6~8总结

时间:2023-06-28 22:44:50浏览次数:46  
标签:总结 题目 String int ArrayList new public name

一.前言

Java编程语言是当今最流行的编程语言之一,由于其跨平台性、面向对象性和安全性等特点,受到广泛的应用。
作为一名计算机专业的学生,在学习Java编程语言时,我们需要完成多个作业来巩固所学知识。
在前三次Java作业中,我们已经学习了Java的基础知识和常用技术,通过完成这些作业,我们更深入地了解了Java编程语言的特点和使用方法。

下面对这三次作业做一个简单的总结:

1.知识点:

 进一步掌握java中类,抽象类及接口的使用,完成成绩计算系列题目。

2.题量与难度:

 题量适中,较为有难度。

3.题目:

实验六:课程成绩统计程序-1

 实验七:容器-HashMap-检索,容器-HashMap-排序,课程成绩统计程序-2,动物发声模拟器(多态)

 实验八:容器-ArrayList-排序, 课程成绩统计程序-3, jmu-Java-02基本语法-03-身份证排序,jmu-Java-04面向对象进阶-03-接口-自定义接口ArrayIntegerStack, jmu-Java-03面向对象基础-05-覆盖

二.设计与分析

1.实验六

7-1 课程成绩统计程序-1
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Student> map = new HashMap<>();
        Scanner sc = new Scanner(System.in);

        while (true) {
            String input = sc.nextLine();
            if (input.equals("end")) {
                break;
            }
            String[] info = input.split(" ");
            String id = info[0];
            String name = info[1];
            int score = Integer.parseInt(info[2]);
            Student student = new Student(name, score);
            map.put(id, student);
        }


        Map<String, Student> sortedMap = new TreeMap<>(
                (o1, o2) -> {
                    int id1 = Integer.parseInt(o1);
                    int id2 = Integer.parseInt(o2);
                    return id2 - id1;
                }
        );
        sortedMap.putAll(map);
        for (Map.Entry<String, Student> entry : sortedMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue().getName() + " " + entry.getValue().getScore());
        }
    }
}


class Student {
    private String name;
    private int score;

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

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }
}

代码如下

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

public class Main{
    public static void main(String[] args){
        Scanner s=new Scanner(System.in);
        String s_record=s.nextLine();
        ParseInput handle=new ParseInput();
        while(!s_record.equals("end")){
            handle.parseInput(s_record);
            s_record=s.nextLine();
        }
        handle.showStudents();
        handle.showCourses();
        handle.showClasses();
    }
}
class Cls implements Comparable<Cls>{
    String Id;
    ArrayList<Student> listStudent=new ArrayList<>();

    public ArrayList<Student> getListStudent() {
        return listStudent;
    }

    public String getId() {
        return Id;
    }
    void addStudent(Student stu){
        listStudent.add(stu);
    }

    public void setId(String Id) {
        this.Id = Id;
    }
    public Cls(String Id){
        this.Id=Id;
    }
    @Override
    public int compareTo(Cls o){
        return Id.compareTo(o.getId());
    }
}
class Student implements Comparable<Student>{
    String Id;
    Cls cls;
    String name;

    public Student(String name,String Id){
        this.name=name;
        this.Id=Id;
    }
    public String getName() {
        return name;
    }

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

    public Cls getCls() {
        return cls;
    }

    public void setCls(Cls cls) {
        this.cls = cls;
    }

    public String getId() {
        return Id;
    }

    public void setId(String Id) {
        this.Id = Id;
    }
    @Override
    public int compareTo(Student o){
        return getId().compareTo(o.getId());
    }
}
class ParseInput{
    ArrayList<Course> listCourse=new ArrayList<>();
    ArrayList<Student> listStudent=new ArrayList<>();
    ArrayList<ChooseCourse> listChooseCourse=new ArrayList<>();
    ArrayList<Cls> listCls=new ArrayList<>();
    public void parseInput(String s){
        int i=InputMatching.matchingInput(s);
        String[] items=s.split(" ");
        if(i == 0){
        System.out.println("wrong format");
        return;
        } else if(i == 1){
        parseCourseRecord(items);
        return;
        } else if(i == 2){
        parseScoreRecord(items);
        return;
        }
    }
    Course getCourse(String courseName){
        for (int i=0;i<listCourse.size();i++)
        {
            if(listCourse.get(i).getName().equals(courseName))
                return listCourse.get(i);
        }
        return null;
    }
    Cls getCls(String clsId){
        for(int i=0;i<listCls.size();i++){
            if(listCls.get(i).getId().equals(clsId))
                return listCls.get(i);
        }
        return null;
    }
    Student getStudent(String stuId){
        for(int i=0;i<listStudent.size();i++)
        {
            if(listStudent.get(i).getId().equals(stuId))
            {
                return listStudent.get(i);
            }

        }
        return null;
    }
    private void parseCourseRecord(String[] items){
        String courseName=items[0];
        String courseType=items[1];
        String checkType=items[2];
        Course course=new Course(courseName,courseType,checkType);
        if(!checkCourse(course))
            return;
        if(getCourse(courseName)==null){
            course=new Course(courseName,courseType,checkType);
            listCourse.add(course);
        }
    }
    boolean checkCourse(Course course){
        int courseTp,accessTp;
        if(course.getType().equals("必修")){
        courseTp = 0;
        } else if(course.getType().equals("选修")){
        courseTp = 1;
        } else {
        courseTp = -1;
        }
        
        if(course.getMethod().equals("考试")){
        accessTp = 0;
        } else if(course.getMethod().equals("考察")){
        accessTp = 1;
        } else {
        accessTp = -1;
        }
        if(courseTp==0&&(accessTp==0))
            return true;
        if(courseTp==1&&(accessTp==0||accessTp==1))
            return true;
        System.out.println(course.getName()+" : course type & access mode mismatch");
        return false;
    }
    private void parseScoreRecord(String[] items){
        String stuId=items[0];
        String stuName=items[1];
        String courseName=items[2];
        String clsId=stuId.substring(0,6);
        Cls cls;
        Student stu;
        cls=getCls(clsId);
        if(cls==null){
            cls=new Cls(clsId);
            listCls.add(cls);
        }
        stu=getStudent(stuId);
        if(stu==null){
            stu=new Student(stuName,stuId);
            listStudent.add(stu);
            cls.addStudent(stu);
        }
        stu.setCls(cls);
        Course course=getCourse(courseName);
        if(course==null){
            System.out.println(courseName+" does not exist");
            return;
        }
        if(!checkGrade(items,course))
            return;
        Grade grade;
        if(items.length==4){
            int finalScore=Integer.parseInt(items[3]);
            grade=new AssessmentGrade(finalScore);
        }else {
            int usualScore=Integer.parseInt(items[3]);
            int finalScore=Integer.parseInt(items[4]);
            grade=new ExaminationGrade(usualScore,finalScore);
        }
        if(existChooseCourse(stu,course)) return;
        ChooseCourse chooseCourse=new ChooseCourse(course,stu,grade);
        listChooseCourse.add(chooseCourse);
    }
    boolean existChooseCourse(Student stu,Course course){
        for(int i=0;i<listChooseCourse.size();i++){
            if(listChooseCourse.get(i).getCourse().getName().equals(course.getName())) {
                if (listChooseCourse.get(i).getStudent().getName().equals(stu.getName()))
                    return true;
            }
        }
        return false;
    }
    private boolean checkGrade(String[] items,Course course){
        String courseType=course.getMethod();
        if(courseType.equals("考试")&&items.length==5){
            return true;
        }
        if(courseType.equals("考察")&&items.length==4){
            return true;
        }
        System.out.println(items[0]+" "+items[1]+" : access mode mismatch");

        return false;
    }
    public void showStudents(){
        Collections.sort(listStudent);
        for(int i =0;i<listStudent.size();i++)
        {
            Student stu=listStudent.get(i);
            ArrayList<ChooseCourse> 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");
            }
        }
    }
    public void showCourses(){
        Collections.sort(listCourse);
        for(int i =0;i<listCourse.size();i++)
        {
            Course course = listCourse.get(i);
            ArrayList<ChooseCourse> courseSelects = getCourseSelects(course.getName());
            if(courseSelects.size()== 0)
            {
                System.out.println(course.getName() + " has no grades yet");
            }
            else {
                if(course.getMethod().equals("考试"))
                {
                    System.out.println(course.getName() + " " +getAvgUsualScore(courseSelects)+ " "+getAvgFinalScore(courseSelects)+ " "+getAvgTotalScore(courseSelects));
                }else{
                    System.out.println(course.getName() + " "+getAvgFinalScore(courseSelects)+ " "+getAvgTotalScore(courseSelects));
                }
            }
        }
    }
    public void showClasses(){
        Collections.sort(listCls);
        for(int i =0;i<listCls.size();i++)
        {
            Cls cls = listCls.get(i);
            ArrayList<ChooseCourse> classCourseSelects = getClassSelects(cls.getId());
            if(classCourseSelects.size()==0){
                System.out.println(cls.getId()+" has no grades yet");
            }
            else{
                System.out.println(cls.getId()+" "+ getAvgTotalScore(classCourseSelects));
            }
        }
    }
    public static int getAvgUsualScore(ArrayList<ChooseCourse> courseSelects)
    {
        int sum = 0;
        for(ChooseCourse cs : courseSelects)
        {
            sum +=((ExaminationGrade) cs.grade).getUsualScore();
        }
        return sum/courseSelects.size();
    }
    public int getAvgTotalScore(ArrayList<ChooseCourse> listChooseCourse)
    {
        int sum =0;
        for(ChooseCourse cs : listChooseCourse)
        {
            sum +=cs.grade.getTotalScore();
        }
        return sum/listChooseCourse.size();
    }
    public int getAvgFinalScore(ArrayList<ChooseCourse> courseSelects)
    {
        int sum =0;
        for(ChooseCourse cs : courseSelects)
        {
            sum +=cs.grade.getFinalScore();
        }
        return sum/courseSelects.size();
    }
    public ArrayList<ChooseCourse> getClassSelects(String className){
        Cls cls=getCls(className);
        ArrayList<ChooseCourse> classSelects = new ArrayList<>();
        for (ChooseCourse cs : listChooseCourse) {
            if (className.equals(cs.getStudent().cls.getId())){
                classSelects.add(cs);
            }
        }
        return classSelects;
    }
    public ArrayList<ChooseCourse> getStudentSelects(String stuId) {
        ArrayList<ChooseCourse> stuSelects = new ArrayList<>();
        for (ChooseCourse cs : listChooseCourse) {
            if (stuId.equals(cs.student.getId())){
                stuSelects.add(cs);
            }
        }
        return stuSelects;
    }
    public ArrayList<ChooseCourse> getCourseSelects(String courseName){
        ArrayList<ChooseCourse> courseSelect=new ArrayList<>();
        for (ChooseCourse cs : listChooseCourse) {
            if (courseName.equals(cs.course.getName())){
                courseSelect.add(cs);
            }
        }
        return courseSelect;
    }

}
class ChooseCourse{
    Course course;
    Student student;
    Grade grade;

    public ChooseCourse(Course course, Student student, Grade grade) {
        this.course=course;
        this.grade=grade;
        this.student=student;
    }

    public Grade getGrade() {
        return grade;
    }

    public Student getStudent() {
        return student;
    }

    public Course getCourse() {
        return course;
    }
}
class InputMatching {
    static String stuNumMatching = "\\d{8}";
    static String stuNameMatching = "[^ \\t]{1,10}";
    static String scoreMatching = "([1-9]?[0-9]|100)";
    static String courseNameMatching = "[^ \\t]{1,10}";
    static String courseTypeMatching = "(选修|必修)";
    static String checkcourseTypeMatching = "(考试|考察)";
    static String scoreMatching1 = "(\\s([1-9]?[0-9]|100))?";
    static String courseInput = courseNameMatching + " " + courseTypeMatching + " " + checkcourseTypeMatching;
    static String scoreInput = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " +
            scoreMatching + scoreMatching1;
    public static int matchingInput(String s) {
        if (matchingCourse(s)) {
            return 1;
        }
        if (matchingScore(s)) {
            return 2;
        }
        return 0;
    }

    private static boolean matchingCourse(String s) {
        return s.matches(courseInput);
    }

    private static boolean matchingScore(String s) {
        return s.matches(scoreInput);
    }
}
class Course implements Comparable<Course>{
    String name;
    String type;
    String method;

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public Course(String name,String type){
        this.type = type;
        this.name = name;
    }
    public Course(String name,String type,String method){
        this.name=name;
        this.type=type;
        this.method=method;
    }
    @Override
    public int compareTo(Course o){
        Comparator<Object> compare=Collator.getInstance(java.util.Locale.CHINA);
        return compare.compare(name,o.getName());
    }
}
abstract class Grade{
    protected int finalScore;
    protected int totalScore;

    public int getTotalScore() {
        return totalScore;
    }

    public int getFinalScore() {
        return finalScore;
    }

    Grade(int finalScore){this.finalScore=finalScore;}
}
class ExaminationGrade extends Grade{
    private int usualScore;

    public int getUsualScore() {
        return usualScore;
    }

    ExaminationGrade(int usualScore, int finalScore){
        super(finalScore);
        this.usualScore=usualScore;
        this.totalScore=(int)(finalScore*0.7+usualScore*0.3);
    }
}
class AssessmentGrade extends Grade{
    AssessmentGrade(int finalScore){
        super(finalScore);
        this.totalScore=finalScore;
    }
}

类图如下

知识点:

一.ArrayList:ArrayList 类继承了 AbstractList 并实现了 List 接口。 ArrayList 支持可以根据需要增长的动态数组。

   ArrayList 类位于 java.util 包中,使用前需要引入它,语法格式如下:

  import java.util.ArrayList; // 引入 ArrayList 类
  ArrayList<E> objectName =new ArrayList<E>();  // 初始化

  • E: 泛型数据类型,用于设置 objectName 的数据类型,只能为引用数据类型。
  •  objectName: 对象名
  1. 添加元素: 使用add()方法将元素添加到ArrayList

  2. 删除元素: 使用remove()方法将元素从ArrayList中删除

计算ArrayList大小: 使用size()方法计算ArrayList大小

  1. 查询ArrayList中特定元素: 使用contains()方法ArrayList中是否有某个元素

  2.  查询ArrayList中特定元素的位置: 使用indexOf()方法查询ArrayList中某个元素的位置

  3. 判断集合是否为空: 使用isEmpty()方法判断集合是否为空

  ArrayList与一般数组的区别

  1. 一般数组在创建时就必须确定大小:

            但是对于ArrayList,你只需要创建出此类型的对象即可。它不需要指定大小,因为它会在加入或删除元素时自动调整大小

   2.存放对象给一般数组时,必须指定位置

    必须要指定在0到比length小1之间的数字,如果索引值超越了数组的限制(例如数组声明为2,但是指定的数字是3),就会报错。

      使用ArrayList时,可以用add(Int, Object)形式的方法来指定索引值,或使用add(Object)形式的方法让它自行管理大小。

二.Collator:Collator 是一个抽象基类,Collator 类执行区分语言环境的 String 比较。使用此类可为自然语言文本构建搜索和排序例程。

三.Comparator:Comparator 是javase中的接口,位于java.util包下

    1. 使用方法:

 Arrays.sort(T[],Comparator<? super T> c);

 Collections.sort(List<T> list,Comparator<? super T> c);

   2. 使用场景: 排序与分组

四.Collection:Collections是⼀个⼯具类,sort是其中的静态⽅法,是⽤来对List类型进⾏排序的,它有两种参数形式:

  public static <T extends Comparable<? super T>> void sort(List<T> list) {
  list.sort(null);
  }

  public static <T> void sort(List<T> list, Comparator<? super T> c) {
  list.sort(c);
  }

2.实验七

7-1 容器-HashMap-检索

代码如下

import java.util.HashMap;
import java.util.Scanner;

class Main{
    public static void main(String[] args) {
        HashMap<String, Student> map = new HashMap<>();
        Scanner sc = new Scanner(System.in);

        while (true) {
            String input = sc.nextLine();
            if (input.equals("end")) {
                break;
            }
            String[] info = input.split(" ");
            String id = info[0];
            String name = info[1];
            int score = Integer.parseInt(info[2]);

            Student student = new Student(id, name, score);
            map.put(id, student);
        }


        String id = sc.nextLine();
        if (map.containsKey(id)) {
            Student student = map.get(id);
            System.out.println(student.getId() + " " + student.getName() + " " + student.getScore());
        } else {
            System.out.println("The student " + id + " does not exist");
        }
    }
}


class Student {
    private String id;
    private String name;
    private int score;

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

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }
}

7-2 容器-HashMap-排序

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Student> map = new HashMap<>();
        Scanner sc = new Scanner(System.in);

        while (true) {
            String input = sc.nextLine();
            if (input.equals("end")) {
                break;
            }
            String[] info = input.split(" ");
            String id = info[0];
            String name = info[1];
            int score = Integer.parseInt(info[2]);
            Student student = new Student(name, score);
            map.put(id, student);
        }


        Map<String, Student> sortedMap = new TreeMap<>(
                (o1, o2) -> {
                    int id1 = Integer.parseInt(o1);
                    int id2 = Integer.parseInt(o2);
                    return id2 - id1;
                }
        );
        sortedMap.putAll(map);
        for (Map.Entry<String, Student> entry : sortedMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue().getName() + " " + entry.getValue().getScore());
        }
    }
}


class Student {
    private String name;
    private int score;

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

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }
}

知识点:HashMap是一个散列表,它存储的内容是键值对(key-value)映射。

1 定义
   public class HashMap<K,V> extends AbstractMap<K,V>
   implements Map<K,V>, Cloneable, Serializable { }

1) HashMap<K,V>表示支持泛型
2)继承自AbstractMap抽象类,实现对于Map容器的操作方法。
3)实现Map接口,实现Map接口中定义的诸多方法。
4)实现Cloneable接口,
5)实现Serializable接口,保证容器的可序列化。

2.核心方法

get(Object key)                            根据key获取value
put(K key, V value)                      存储键值对 
containsKey(Object key)             是否包含key 
containsValue(Object value)       是否包含value 
remove(Object key)                     删除key对应的value 
size()                                           容器元素数目 
isEmpty()                                     集合是否为空 
clear()                                          清空集合 

3. 小结
HashMap采用数组+链表的方式存储键值对,当链表长度超过限定阈值,则将链表结构调整为红黑树,提高查找效率。通过源码可以看出在添加键值对时没有null检查,因此HashMap是允许null值的。

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

代码如下

import java.util.*;

class Course {
    String name;
    String nature;
    String assessment;

    Course(String name, String nature, String assessment) {
        this.name = name;
        this.nature = nature;
        this.assessment = assessment;
    }
}

class Grade {
    String studentId;
    String name;
    String courseName;
    Integer regularScore;
    Integer finalScore;

    Grade(String studentId, String name, String courseName, Integer regularScore, Integer finalScore) {
        this.studentId = studentId;
        this.name = name;
        this.courseName = courseName;
        this.regularScore = regularScore;
        this.finalScore = finalScore;
    }
}

class LabGrade {
    String studentId;
    String name;
    String courseName;
    List<Integer> experimentScores;

    LabGrade(String studentId, String name, String courseName, List<Integer> experimentScores) {
        this.studentId = studentId;
        this.name = name;
        this.courseName = courseName;
        this.experimentScores = experimentScores;
    }
}

public class CourseGradeStatistics {
    private List<Course> courses = new ArrayList<>();
    private List<Grade> grades = new ArrayList<>();
    private List<LabGrade> labGrades = new ArrayList<>();

    public static void main(String[] args) {
        CourseGradeStatistics statistics = new CourseGradeStatistics();
        statistics.run();
    }

    private void run() {
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();

            if (line.isEmpty()) {
                break;
            }

            if (line.startsWith("学号")) {
                parseGrade(line);
            } else if (line.startsWith("实验")) {
                parseLabGrade(line);
            } else {
                parseCourse(line);
            }
        }

        scanner.close();

        List<String> studentAverages = calculateStudentAverage();
        List<String> courseAverages = calculateCourseAverage();
        List<String> classAverages = calculateClassAverage();

        // 输出学生所有课程总成绩平均分
        for (String average : studentAverages) {
            System.out.println(average);
        }

        // 输出单门课程成绩平均分
        for (String average : courseAverages) {
            System.out.println(average);
        }

        // 输出班级所有课程总成绩平均分
        for (String average : classAverages) {
            System.out.println(average);
        }
    }

    private void parseCourse(String courseInfo) {
        String[] info = courseInfo.split("\\s+");
        String name = info[0];
        String nature = info[1];
        String assessment = null;
        if (info.length == 3) {
            assessment = info[2];
        }
        Course course = new Course(name, nature, assessment);
        courses.add(course);
    }

    private void parseGrade(String gradeInfo) {
        String[] info = gradeInfo.split("\\s+");
        String studentId = info[0];
        String name = info[1];
        String courseName = info[2];
        Integer regularScore = null;
        Integer finalScore = null;
        if (info.length == 5) {
            regularScore = Integer.parseInt(info[3]);
            finalScore = Integer.parseInt(info[4]);
        } else if (info.length == 4) {
            finalScore = Integer.parseInt(info[3]);
        }
        Grade grade = new Grade(studentId, name, courseName, regularScore, finalScore);
        grades.add(grade);
    }

    private void parseLabGrade(String labGradeInfo) {
        String[] info = labGradeInfo.split("\\s+");
        String studentId = info[0];
        String name = info[1];
        String courseName = info[2];
        List<Integer> experimentScores = new ArrayList<>();
        for (int i = 3; i < info.length; i++) {
            experimentScores.add(Integer.parseInt(info[i]));
        }
        LabGrade labGrade = new LabGrade(studentId, name, courseName, experimentScores);
        labGrades.add(labGrade);
    }

    private List<String> calculateStudentAverage() {
        Map<String, List<Integer>> studentScores = new HashMap<>();

        for (Grade grade : grades) {
            List<Integer> scores = studentScores.getOrDefault(grade.courseName, new ArrayList<>());
            scores.add(grade.finalScore);
            studentScores.put(grade.courseName, scores);
        }

        for (LabGrade labGrade : labGrades) {
            List<Integer> scores = studentScores.getOrDefault(labGrade.courseName, new ArrayList<>());
            int totalScore = labGrade.experimentScores.stream().mapToInt(Integer::intValue).sum();
            int averageScore = totalScore / labGrade.experimentScores.size();
            scores.add(averageScore);
            studentScores.put(labGrade.courseName, scores);
        }

        List<String> studentAverages = new ArrayList<>();

        for (Map.Entry<String, List<Integer>> entry : studentScores.entrySet()) {
            String courseName = entry.getKey();
            List<Integer> scores = entry.getValue();
            int average = scores.stream().mapToInt(Integer::intValue).sum() / scores.size();
            studentAverages.add(courseName + " " + average);
        }

        studentAverages.sort(Comparator.comparing(String::toLowerCase));

        return studentAverages;
    }

    private List<String> calculateCourseAverage() {
        List<String> courseAverages = new ArrayList<>();

        for (Course course : courses) {
            if (course.assessment.equals("实验")) {
                List<Integer> scores = new ArrayList<>();
                for (Grade grade : grades) {
                    if (grade.courseName.equals(course.name)) {
                        scores.add(grade.finalScore);
                    }
                }
                for (LabGrade labGrade : labGrades) {
                    if (labGrade.courseName.equals(course.name)) {
                        scores.add(labGrade.experimentScores.stream().mapToInt(Integer::intValue).sum() /
                                   labGrade.experimentScores.size());
                    }
                }
                int average = scores.stream().mapToInt(Integer::intValue).sum() / scores.size();
                courseAverages.add(course.name + " " + average);
            } else {
                List<Integer> regularScores = new ArrayList<>();
                List<Integer> finalScores = new ArrayList<>();
                for (Grade grade : grades) {
                    if (grade.courseName.equals(course.name)) {
                        if (grade.regularScore != null) {
                            regularScores.add(grade.regularScore);
                        }
                        finalScores.add(grade.finalScore);
                    }
                }
                int regularAverage = regularScores.stream().mapToInt(Integer::intValue).sum() / regularScores.size();
                int finalAverage = finalScores.stream().mapToInt(Integer::intValue).sum() / finalScores.size();
                int totalAverage = (int) (regularAverage * 0.3 + finalAverage * 0.7);
                courseAverages.add(course.name + " " + regularAverage + " " + finalAverage + " " + totalAverage);
            }
        }

        courseAverages.sort(Comparator.comparing(String::toLowerCase));

        return courseAverages;
    }

    private List<String> calculateClassAverage() {
        Map<String, List<Integer>> classScores = new HashMap<>();

        for (Grade grade : grades) {
            String classId = grade.studentId.substring(0, 6);
            List<Integer> scores = classScores.getOrDefault(classId, new ArrayList<>());
            scores.add(grade.finalScore);
            classScores.put(classId, scores);
        }

        for (LabGrade labGrade : labGrades) {
            String classId = labGrade.studentId.substring(0, 6);
            List<Integer> scores = classScores.getOrDefault(classId, new ArrayList<>());
            int totalScore = labGrade.experimentScores.stream().mapToInt(Integer::intValue).sum();
            int averageScore = totalScore / labGrade.experimentScores.size();
            scores.add(averageScore);
            classScores.put(classId, scores);
        }

        List<String> classAverages = new ArrayList<>();

        for (Map.Entry<String, List<Integer>> entry : classScores.entrySet()) {
            String classId = entry.getKey();
            List<Integer> scores = entry.getValue();
            int average = scores.stream().mapToInt(Integer::intValue).sum() / scores.size();
            classAverages.add(classId + " " + average);
        }

        classAverages.sort(Comparator.comparing(String::toLowerCase));

        return classAverages;
    }
}

 

类图如下

 本题目在课程成绩统计系统1的基础上进行了改进,较有难度

3.实验八

7-1 容器-ArrayList-排序

代码如下

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

class Student {
    private String id;
    private String name;
    private int mathScore;
    private int physicsScore;

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

    public int getTotalScore() {
        return mathScore + physicsScore;
    }

    public String toString() {
        return id + " " + name + " " + getTotalScore();
    }
}

class Main {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            String input = scanner.nextLine();
            if (input.equals("end")) {
                break;
            }

            String[] tokens = input.split(" ");
            String id = tokens[0];
            String name = tokens[1];
            int mathScore = Integer.parseInt(tokens[2]);
            int physicsScore = Integer.parseInt(tokens[3]);

            Student student = new Student(id, name, mathScore, physicsScore);
            studentList.add(student);
        }

        Collections.sort(studentList, Comparator.comparing(Student::getTotalScore).reversed());

        for (Student student : studentList) {
            System.out.println(student);
        }
    }
}

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

代码如下

import java.util.*;

class Course {
    String name;
    String nature;
    String assessment;

    Course(String name, String nature, String assessment) {
        this.name = name;
        this.nature = nature;
        this.assessment = assessment;
    }
}

class Grade {
    String studentId;
    String name;
    String courseName;
    int regularScore;
    int finalScore;

    Grade(String studentId, String name, String courseName, int regularScore, int finalScore) {
        this.studentId = studentId;
        this.name = name;
        this.courseName = courseName;
        this.regularScore = regularScore;
        this.finalScore = finalScore;
    }
}

public class GradeStatistics {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        List<Course> courses = new ArrayList<>();
        List<Grade> grades = new ArrayList<>();

        // 读取课程信息
        while (true) {
            String line = scanner.nextLine().trim();

            if (line.isEmpty()) {
                break;
            }

            String[] courseInfo = line.split(" ");
            String name = courseInfo[0];
            String nature = courseInfo[1];
            String assessment = courseInfo[2];

            Course course = new Course(name, nature, assessment);
            courses.add(course);
        }

        // 读取成绩信息
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();

            if (line.isEmpty()) {
                break;
            }

            String[] gradeInfo = line.split(" ");
            String studentId = gradeInfo[0];
            String name = gradeInfo[1];
            String courseName = gradeInfo[2];
            int regularScore = Integer.parseInt(gradeInfo[3]);
            int finalScore = Integer.parseInt(gradeInfo[4]);

            Grade grade = new Grade(studentId, name, courseName, regularScore, finalScore);
            grades.add(grade);
        }

        scanner.close();

        // 计算成绩统计结果
        Map<String, List<Integer>> studentScores = new HashMap<>();  // 每个学生的成绩列表

        for (Grade grade : grades) {
            List<Integer> scores = studentScores.getOrDefault(grade.studentId, new ArrayList<>());
            scores.add(grade.finalScore);
            studentScores.put(grade.studentId, scores);
        }

        List<String> studentAverages = new ArrayList<>();  // 每个学生的平均分

        for (Map.Entry<String, List<Integer>> entry : studentScores.entrySet()) {
            String studentId = entry.getKey();
            List<Integer> scores = entry.getValue();
            int sum = scores.stream().mapToInt(Integer::intValue).sum();
            int average = sum / scores.size();
            studentAverages.add(studentId + " " + average);  // 学号 平均分
        }

        studentAverages.sort(Comparator.comparing(String::toLowerCase));

        // 输出结果
        for (String average : studentAverages) {
            System.out.println(average);
        }
    }
}

类图如下

 

本题目对前两次的课程成绩统计系统进行了进一步的改进,难度进一步提升,在规定的作业截至时间内并没有写出正确的代码,在作业截止后又对题目进行了研究。

 7-3 jmu-Java-02基本语法-03-身份证排序

代码如下

import java.util.*;
 
public class Main {
 
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        scan.nextLine();
        String A[] = new String[n], C[] = new String[n];
        for (int i = 0; i < n; i++) {
            A[i] = scan.nextLine();
        }
 
        String B = scan.nextLine();
 
        for (; B.equals("sort1") || B.equals("sort2");) {
            if (B.equals("sort1")) {
                for (int j = 0; j < n; j++) {
                    C[j] = A[j].substring(6, 10) + "-" + A[j].substring(10, 12) + "-" + A[j].substring(12, 14);
                }
                Arrays.sort(C);
                for (int j = 0; j < n; j++) {
                    System.out.println(C[j].toString());
                }
            } else if (B.equals("sort2")) {
                for (int j = 0; j < n; j++) {
                    C[j] = A[j].substring(6, 14);
                }
                Arrays.sort(C);
                for (int j = 0; j < n; j++)
                    for (int k = 0; k < n; k++)
                        if (A[k].contains(C[j]))
                            System.out.println(A[k].toString());
            }
            System.out.println("exit");
            B = scan.nextLine();
        }
 
        scan.close();
    }
 
}

1.sort函数,对一维数组元素,进行升序排列

用法: Arrays.sort(数组名称);

static void sort(ElementType[] a)
默认为升序排序
static void sort(ElementType[] a, int FromIndex, int ToIndex)
在指定范围(FromIndex, ToIndex)内升序排序
static void sort(T[] a, Comparator<? super T> c)
根据指定的比较器指定的顺序,对指定的对象数组进行排序。

底层原理:插入排序+二分查找

开始的默认0索引的数据是有序序列,然后遍历数组后面的每一个元素,将每一个元素插入到前面有序序列的指定地方。

7-4 jmu-Java-04面向对象进阶-03-接口-自定义接口ArrayIntegerStack

代码如下

import java.util.Arrays;
import java.util.Scanner;

interface IntegerStack {
    public Integer push(Integer item); //如果item为null,则不入栈直接返回null。如果栈满,也返回null。如果插入成功,返回item
    public Integer pop();   //出栈,如果为空,则返回null。出栈时只移动栈顶指针,相应位置不置为null
    public Integer peek();  //获得栈顶元素,如果为空,则返回null
    public boolean empty(); //如果为空返回true
    public int size();      //返回栈中元素个数
}

class ArrayIntegerStack implements IntegerStack{
    private Integer[] arr;
    private int top = 0;

    public ArrayIntegerStack(int n){
        arr = new Integer[n];
        Arrays.fill(arr, null);
    }

    public ArrayIntegerStack(){}

    @Override
    public String toString() {
        return Arrays.toString(arr);
    }

    @Override
    public Integer push(Integer item) {
        if (item == null || arr.length == top){
            return null;
        }
        arr[top++] = item;
        return item;
    }

    @Override
    public Integer pop() {
        if (top == 0){
            return null;
        }
        return arr[--top];
    }

    @Override
    public Integer peek() {
        if (top == 0){
            return null;
        }
        return arr[top - 1];
    }

    @Override
    public boolean empty() {
        return top == 0;
    }

    @Override
    public int size() {
        return top;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        ArrayIntegerStack ais = new ArrayIntegerStack(n);
        int m = scanner.nextInt();
        while(m-- > 0){
            int item = scanner.nextInt();
            System.out.println(ais.push(item));
        }
        System.out.println(ais.peek() + "," + ais.empty() + "," + ais.size());
        System.out.println(ais);
        int x = scanner.nextInt();
        while(x-- > 0){
            System.out.println(ais.pop());
        }
        System.out.println(ais.peek() + "," + ais.empty() + "," + ais.size());
        System.out.println(ais);
    }
}

知识点:

1.栈的定义
栈(Stack) 是一种 后进先出(LIFO:Last In First Out) 的数据结构。

队列(Queue) 是先进先出 (First In First Out, FIFO) 的数据结构,是最先进队列的元素一定最早出队列。

2. 栈的基本操作
Stack只有入栈和出栈的操作:

把元素压栈:push(E);
把栈顶的元素“弹出”:pop();
取栈顶元素但不弹出:peek()。
在Java中,我们用Deque可以实现Stack的功能:

把元素压栈:push(E)/addFirst(E); 把栈顶的元素“弹出”:pop()/removeFirst();
取栈顶元素但不弹出:peek()/peekFirst()。

3.Java中栈的应用
empty()                  boolean               测试堆栈是否为空
push(E item)              E                     把项压入堆栈顶部
pop()                          E                     移除堆栈顶部的对象,并作为此函数的值返回该对象
peek()                        E                     查看堆栈顶部的对象,但不从堆栈中移除它
search(Object o)       int                    返回对象再堆栈中的位置,以1为基数
4.初始化
Stack stack=new Stack();

7-5 jmu-Java-03面向对象基础-05-覆盖

代码如下

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
       Scanner sc=new Scanner(System.in);
       int n1= sc.nextInt();
       boolean f=true;
       sc.nextLine();
       ArrayList<PersonOverride> ap=new ArrayList<PersonOverride>();
        for (int i=0;i<n1;i++){
            ap.add(new PersonOverride());
        }
        int n2= sc.nextInt();
        sc.nextLine();
        for (int i=0;i<n2;i++){
            f=true;
            PersonOverride a=new PersonOverride(sc.next(),sc.nextInt(), sc.nextBoolean());
            sc.nextLine();
            for (PersonOverride aa:ap) {
                if (aa.equals(a)){
                    f=false;
                    break;
                }
            }
            if (f)ap.add(a);
        }

        for(PersonOverride a:ap){
            System.out.println(a.toString().replace("[","").replace("]",""));
        }
        System.out.println(ap.size()-n1);
        System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));
    }

}

class PersonOverride{
    private String name;
    private  int age;
    private boolean gender;

    public PersonOverride() {
        this("default",1,true);
    }

    public PersonOverride(String name, int age, boolean gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }


    @Override
    public String toString() {
        return name + "-" + age + "-" + gender;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PersonOverride that = (PersonOverride) o;
        return age == that.age &&
                gender == that.gender &&
                name.equals(that.name);
    }

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

知识点:

一.equals

  1.是一个方法,而非运算符

   2.只能适用于引用数据类型

   3.Object类中equls()的定义:
     public boolean equals(Object obj) {
     return (this == obj);
     }
     Object类定义的equals()和==的作用是相同的,比较俩地址值是否相同。

   4.踩坑及难点

(1).equals是object类中的方法,只能用于判断引用类型。

(2).equals方法默认判断的是地址是否相等,子类中往往重写该方法,用于判断内容是否相等。比如String和Integer类中的equals源代码。

 

 

三.课程成绩统计分析

  1. 创建一个课程类(Course),包含课程名称、性质(实验/非实验)、考核方式(考试/其他)等属性。
 class Course { String name; String nature; String assessment; Course(String name, String nature, String assessment) { this.name = name; this.nature = nature; this.assessment = assessment; } }
  1. 创建一个成绩类(Grade),包含学生的学号、姓名、课程名称、平时成绩、期末成绩等属性。

class Grade { String studentId; String name; String courseName; int regularScore; int finalScore; Grade(String studentId, String name, String courseName, int regularScore, int finalScore) { this.studentId = studentId; this.name = name; this.courseName = courseName; this.regularScore = regularScore; this.finalScore = finalScore; } }

  1. 创建一个存储课程和成绩的容器,可以使用数组、ArrayList等数据结构来存储。

List<Course> courses = new ArrayList<>(); List<Grade> grades = new ArrayList<>();

  1. 读取输入信息,并解析出课程和成绩信息,将其存储到相应的容器中。

  2. 根据题目要求,计算成绩的统计结果,比如每个学生的总平均分、每门课程的平均分、班级的平均分等。

  3. 输出计算结果。

四.总结

    1.难度逐渐上升,需要熟练的掌握Java中类的使用及Object和String类中一些方法的使用。其中,最主要的是对类的使用,如类的继承、封装和多态性等。更加深入地理解面向对象的编程思想,熟悉Java编程语言的类和对象的使用方法。重点是对Javabean的基本使用,类的广泛应用。通过这些练习,我们可以更深入地掌握Java编程语言的常用技术,如数据结构、输入输出、异常处理等。

 

五.改进建议

  逻辑有些混乱,不能理清思路导致不能流畅地写出代码,并且使用的算法较为复杂,有些题目是可以用到更简单的方法,有许多简单易懂的算法和思路。

 

 

标签:总结,题目,String,int,ArrayList,new,public,name
From: https://www.cnblogs.com/lsy--/p/17509834.html

相关文章

  • 6-8题目集
    前言:在这个六到八次题目集中,主要用课程管理系统来考察以下的知识点,:输入输出、字符串处理、数据结构(HashMap、ArrayList、List、Set)、循环、条件判断、类与对象、继承与多态、异常处理等。题量从小变大,难度大的也主要是那些学生课程成绩管理系统的解决,输入信息的解析和存储、成绩......
  • 第六到第八次题目集总结
    第六到第八次题目集总结一、题目集六课程成绩统计程序-1第一题题目内容:课程成绩统计程序-1publicclassGrade{privatefinalCourseGradecourseGrade;privatefinalSubGradesubGrade;publicGrade(CourseGradecourseGrade,SubGradesubGrade){......
  • 6-8次PTA题目总结blog
    前言:题目集1~3的知识点、题量、难度等情况如下:知识点:JAVA基础,基础算法,面向对象程序设计题量:共计3道题目难度:题目从易到难,逐层递进,分别为考察Java容器的理解、掌握与运用。设计与分析: 1importjava.util.*;2importjava.util.regex.Pattern;3impo......
  • PTA题目集6-8总结
    (1)前言题目集6只有一个课程成绩统计程序-1,难点总体来说中等,考察的也是对java类的定义和使用,以及如何设计能使程序往后修改方便,可以根据给出的类图来进行设计。题目集7中有上一次程序的进阶版课程成绩统计程序-2,相比于之前添加了实验这一课程性质,总的来说改变不大,只需要在......
  • PTA题目集6~8
    (1)前言前面的点菜系统结束后,以为终于解脱了,没想到是另一个噩梦。以下是PTA6到8的相关问题。题目集6,只有一题,课程成绩统计程序-1,难度嘛,中等偏上吧,至少对我来说,因为我接口基本没学懂。题目集7,有四题,容器-HashMap-检索,容器-HashMap-排序,课程成绩统计程序-2,动物发声模拟器(多态)。前面......
  • pta题目集6~8次总结性blog
    一、前言总结三次题目集的知识点、题量、难度等情况第六次题目集开始了新的迭代系统,万恶的点菜系统终于结束了,取而代之的是课程成绩统计程序,虽说更换了迭代系统但是感觉换汤不换药,很多要用到的知识点和内容和菜单非常类似,甚至是比点菜系统要简单很多(听说是不让平时分那么难看),万......
  • 面向对象程序编程6-8次PTA题目集(成绩计算系列)的总结性Blog
    1.对之前发布的6-8次PTA题目集(成绩计算系列),内容要求如下:(1)前言:总结之前所涉及到的知识点、题量、难度等情况第六次PTA题目集:知识点:此次PTA题目仅只有这一个题目,主要考的内容就是对类的使用(类似现实,对有关联的各个数据合并在一起,便于一起使用),运用正则表达式(比较苦难使用,要记住那......
  • 6-8次PTA题目集总结
    6-8次PTA题目集总结前言第6次题目集知识点:对象和类的创建和应用,字符串的创建和应用。总共有1题,难度偏低,比较基础。第7次题目集知识点:HashMap的创建和使用,多态,对象和类的创建和应用,字符串的创建和应用。总共有4题,难度中等。第8次题目集知识点:ArrayList的创建和使用,接口的......
  • 6-8次PTA题目集(成绩计算系列)分析
      前言知识点:类和对象:定义班级、学生和课程等类,并创建相应的对象;封装和访问控制:使用private、public等关键字对类的字段进行封装和访问控制;集合类:使用ArrayList或者其他集合类存储学生和课程信息;输入输出:通过控制台或者文件读写来输入和输出学生课程成绩信息;循环和条......
  • 性能测试理论、定位、分析总结
    一、理论1.1概念性能测试针对系统的性能指标,建立性能测试模型,制定性能测试方案,制定监控策略,在场景条件之下执行性能场景,分析判断性能瓶颈并调优,最终得出性能结果来评估系统的性能指标是否满足既定值。1.2性能指标指标包括:时间指标、容量指标和资源利用率指标时间指标指......