本周的作业是第三次博客,也是本课程的最后一次博客,本次博客主要有PTA题目集合7、8以及期末考试题,PTA题目7由四个小题目组成,容器hashmap检索,容器hashmap排序,课程统计程序2,动物发声模拟器,除去课程统计程序2,另外 三个看起来比较简单,但我也不太会。
以下是本次实验的部分代码。
第一题是hashmap检索
import java.util.Scanner; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String line = sc.nextLine(); HashMap <String,Student> map = new HashMap<>(); while (!line.equals("end")){ String[] arr = line.split(" "); Student student = new Student(arr[0],arr[1],arr[2] ) ; map.put(arr[0],student); line = sc.nextLine(); } line =sc.nextLine(); if(map.containsKey(line)){ System.out.println(map.get(line).getid()+" "+map.get(line).getName()+" "+map.get(line).getScore()); return; } System.out.printf("The student %s does not exist",line); } } class Student { String id; ; String name ; String score; public Student(){} public String getName() { return name; } public String getScore() { return score; } public String getid() { return id; } public Student(String id,String name,String score) { this.name = name; this.id = id; this.score = score; } }
hashmap的排序
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); HashMap <String,String> map = new HashMap<>(); while (!str.equals("end")){ String[] arr = str.split(" "); Student student = new Student(arr[0],arr[1],arr[2] ) ; map.put(arr[1]+" "+arr[2],arr[0]); str = sc.nextLine(); } TreeMap <String,String> sortedmap = new TreeMap<>(new Comparator<String>() { public int compare(String o1, String o2) { return map.get(o2).compareTo(map.get(o1)); } }); sortedmap.putAll(map); for (String key:sortedmap.keySet()){ System.out.println(sortedmap.get(key)+" "+key); } } } class Student { private String id ; private String name ; private String score; public Student(){} public Student(String id,String name,String score) { this.id = id; this.name = name; this.score = score; } public String getName() { return name; } public String getScore() { return score; } public String getid() { return id; } }
动物发声模拟器,这个小题主要用到了多态,猫狗山羊都属于动物类,但每个动物都有自己的行为,同一类行为有着不同的表达方式,多态是同一个行为具有多个不同表现形式或形态的能力。多态就是同一个接口,使用不同的实例而执行不同操作。
public class Main { public static void main(String[] args) { Animals cat = new Cat(); Animals dog = new Dog(); Animals goat = new Goat(); speak(cat); speak(dog); speak(goat); } public static void speak(Animals animal) { System.out.println(animal.getAnimalClass() + "的叫声:" + animal.shout()); } } abstract class Animals { abstract public String getAnimalClass(); abstract public String shout(); } class Cat extends Animals { public String getAnimalClass() { return "猫"; } public String shout() { return "喵喵"; } } class Dog extends Animals { public String getAnimalClass() { return "狗"; } public String shout() { return "汪汪"; } } class Goat extends Animals{ public String getAnimalClass() { return "山羊"; } public String shout() { return "咩咩"; } }
课程统计程序2,本次课程统计程序2继承了之前的课程统计程序1,但是第一次的课程统计程序1也完成的不是很好,所以导致了后面的也都不会
课程成绩统计程序-2在第一次的基础上增加了实验课,以下加粗字体显示为本次新增的内容。
某高校课程从性质上分为:必修课、选修课、实验课,从考核方式上分为:考试、考察、实验。
考试的总成绩由平时成绩、期末成绩分别乘以权重值得出,比如平时成绩权重0.3,期末成绩权重0.7,总成绩=平时成绩*0.3+期末成绩*0.7。
考察的总成绩直接等于期末成绩
实验的总成绩等于课程每次实验成绩的平均分
必修课的考核方式必须为考试,选修课可以选择考试、考察任一考核方式。实验课的成绩必须为实验。
1、输入:
包括课程、课程成绩两类信息。
课程信息包括:课程名称、课程性质、考核方式(可选,如果性质是必修课,考核方式可以没有)三个数据项。
课程信息格式:课程名称+英文空格+课程性质+英文空格+考核方式
课程性质输入项:必修、选修、实验
考核方式输入选项:考试、考察、实验
考试/考查课程成绩信息包括:学号、姓名、课程名称、平时成绩(可选)、期末成绩
考试/考查课程信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+平时成绩+英文空格+期末成绩
实验课程成绩信息包括:学号、姓名、课程名称、实验次数、每次成绩
实验次数至少4次,不超过9次
实验课程信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+实验次数+英文空格+第一次实验成绩+...+英文空格+最后一次实验成绩
以上信息的相关约束:
1)平时成绩和期末成绩的权重默认为0.3、0.7
2)成绩是整数,不包含小数部分,成绩的取值范围是【0,100】
3)学号由8位数字组成
4)姓名不超过10个字符
5)课程名称不超过10个字符
6)不特别输入班级信息,班级号是学号的前6位。
2、输出:
输出包含三个部分,包括学生所有课程总成绩的平均分、单门课程成绩平均分、单门课程总成绩平均分、班级所有课程总成绩平均分。
为避免误差,平均分的计算方法为累加所有符合条件的单个成绩,最后除以总数。
1)学生课程总成绩平均分按学号由低到高排序输出
格式:学号+英文空格+姓名+英文空格+总成绩平均分
如果某个学生没有任何成绩信息,输出:学号+英文空格+姓名+英文空格+"did not take any exams"
2)单门课程成绩平均分分为三个分值:平时成绩平均分(可选)、期末考试平均分、总成绩平均分,按课程名称的字符顺序输出
考试/考察课程成绩格式:课程名称+英文空格+平时成绩平均分+英文空格+期末考试平均分+英文空格+总成绩平均分
实验课成绩格式:课程名称+英文空格+总成绩平均分
如果某门课程没有任何成绩信息,输出:课程名称+英文空格+"has no grades yet"
3)班级所有课程总成绩平均分按班级由低到高排序输出
格式:班级号+英文空格+总成绩平均分
如果某个班级没有任何成绩信息,输出:班级名称+英文空格+ "has no grades yet"
异常情况:
1)如果解析某个成绩信息时,课程名称不在已输入的课程列表中,输出:学号+英文空格+姓名+英文空格+":"+课程名称+英文空格+"does not exist"
2)如果解析某个成绩信息时,输入的成绩数量和课程的考核方式不匹配,输出:学号+英文空格+姓名+英文空格+": access mode mismatch"
以上两种情况如果同时出现,按第一种情况输出结果。
3)如果解析某个课程信息时,输入的课程性质和课程的考核方式不匹配,输出:课程名称+" : course type & access mode mismatch"
4)格式错误以及其他信息异常如成绩超出范围等,均按格式错误处理,输出"wrong format"
5)若出现重复的课程/成绩信息,只保留第一个课程信息,忽略后面输入的。
信息约束:
1)成绩平均分只取整数部分,小数部分丢弃
import java.text.Collator; import java.util.*; 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.sortmyinstance(); handle.scorestudent(); handle.scorecourse(); handle.scoreclass(); } } class ParseInput{ private final ArrayList<SelectCourse> selectCourses = new ArrayList<>(); private final ArrayList<Course> courses = new ArrayList<>(); private final ArrayList<Student> students = new ArrayList<>(); private final ArrayList<String> Class = new ArrayList<>(); private final HashMap<String,String> courseMethod=new HashMap(); int panid=1; public void parseInput(String input){ String []arr=input.split(" "); if(InputMatching.matchingInput(input)==1){ courseMethod.put(arr[0],arr[2]); if(checkCourse(arr[0])!=null)return; else { if(arr[1].equals("必修")&&(!arr[2].equals("考试"))){ System.out.println(arr[0]+" : course type & access mode mismatch"); if(panid<0) { System.out.println("必修"); System.out.println("选修"); System.out.println("实验"); } } else if(arr[1].equals("选修")&&!(arr[2].equals("考试")||arr[2].equals("考察"))){ System.out.println(arr[0]+" : course type & access mode mismatch"); } else if(arr[1].equals("实验")&&!(arr[2].equals("实验"))){ System.out.println(arr[0]+" : course type & access mode mismatch"); } else courses.add(new Course(arr[0],arr[1],arr[2])); } } else if(InputMatching.matchingInput(input)==2){ Course findcourse=checkCourse(arr[2]); if(arr.length>5&&(Integer.parseInt(arr[3])<4||Integer.parseInt(arr[3])>9)) { System.out.println("wrong format"); return; } Student newStudent = new Student(arr[0],arr[1]); if(!checkStudent(newStudent.getNum()))students.add(newStudent); if(!checkClass(arr[0].substring(0,6))){ Class.add(arr[0].substring(0,6)); } if(checkSelect(arr[0],arr[2]))return; if(findcourse==null){ System.out.println(arr[2]+" does not exist"); return; } else if(findcourse.getMethod().equals("考试")&&arr.length!=5){ System.out.println(arr[0]+' '+arr[1]+" : access mode mismatch"); } else if(findcourse.getMethod().equals("考察")&&arr.length!=4){ System.out.println(arr[0]+' '+arr[1]+" : access mode mismatch"); } else if(findcourse.getMethod().equals("实验")&&(arr.length-4!=Integer.parseInt(arr[3]))){ System.out.println(arr[0]+' '+arr[1]+" : access mode mismatch"); } else{ SelectCourse newSelectCourse=new SelectCourse(); newSelectCourse.setCourse(findcourse); Grade grade=null; if(findcourse.getMethod().equals("考试")){ ExamGrade examGrade=new ExamGrade(); examGrade.setUsualGrade(Integer.parseInt(arr[3])); examGrade.setFinalGrade(Integer.parseInt(arr[4])); grade=examGrade; } else if(findcourse.getMethod().equals("实验")){ NoExamGrade noExamGrade=new NoExamGrade(); double sumScore=0; for (int i=4;i<arr.length;i++)sumScore+=Integer.parseInt(arr[i]); noExamGrade.setFinalGrade((int)(sumScore/Integer.parseInt(arr[3]))); grade=noExamGrade; } else { NoExamGrade noExamGrade=new NoExamGrade(); noExamGrade.setFinalGrade(Integer.parseInt(arr[3])); grade=noExamGrade; } newSelectCourse.setGrade(grade); newSelectCourse.setStudent(newStudent); selectCourses.add(newSelectCourse); } } else System.out.println("wrong format"); } private Course checkCourse(String courseName){ for (Course course:courses){ if(course.getName().equals(courseName))return course; } return null; } private Boolean checkStudent(String num){ for (Student student:students){ if(student.getNum().equals(num))return true; } return false; } private Boolean checkClass(String classnum){ for (String cname:Class){ if(cname.equals(classnum))return true; } return false; } private Boolean checkSelect(String stunum,String cname){ for (SelectCourse selectCourse:selectCourses){ if(selectCourse.getStudent().getNum().equals(stunum)&&selectCourse.getCourse().getName().equals(cname))return true; } return false; } public void scorestudent(){ for (Student student:students){ double sum=0; int count=0; for (SelectCourse selectCourse:selectCourses){ if (selectCourse.getStudent().getNum().equals(student.getNum())) { sum+=selectCourse.getGrade().getTotalGrade(); count++; } } if(count==0) System.out.println(student.getNum()+' '+student.getName()+' '+"did not take any exams"); else System.out.println(student.getNum()+' '+student.getName()+' '+(int)(sum/count)); } } public void scorecourse(){ for (Course course:courses){ double sumUsualScore=0; double sumFinalScore=0; double sumTotalScore=0; int count=0; for(SelectCourse selectCourse:selectCourses){ if(selectCourse.getCourse().getName().equals(course.getName())){ count++; sumTotalScore+=selectCourse.getGrade().getTotalGrade(); sumFinalScore+=selectCourse.getGrade().getFinalGrade(); if(selectCourse.getCourse().getMethod().equals("考试")){ sumUsualScore+=selectCourse.getGrade().getUsualGrade(); } } } if (count==0) System.out.println(course.getName()+' '+"has no grades yet"); else if(course.getMethod().equals("考试"))System.out.println(course.getName()+' '+(int)(sumUsualScore/count)+' '+(int)(sumFinalScore/count)+' '+(int)(sumTotalScore/count)); else if(course.getMethod().equals("考察"))System.out.println(course.getName()+' '+(int)(sumFinalScore/count)+' '+(int)(sumTotalScore/count)); else if(course.getMethod().equals("实验"))System.out.println(course.getName()+' '+(int)(sumFinalScore/count)); } } public void scoreclass(){ for (String classnum:Class){ double sum=0; int count=0; for (SelectCourse selectCourse:selectCourses){ if(selectCourse.getStudent().getNum().substring(0,6).equals(classnum)){ sum+=selectCourse.getGrade().getTotalGrade(); count++; } } if(count==0) System.out.println(classnum+' '+"has no grades yet"); else System.out.println(classnum+' '+(int)(sum/count)); } } public void sortmyinstance(){ students.sort(Comparator.comparing(Student::getNum)); courses.sort((x,y)->{ Collator instance = Collator.getInstance(Locale.CHINA); return instance.compare(x.getName(), y.getName()); } ); Collections.sort(Class); } } abstract class Grade{ double TotalGrade; public int getTotalGrade() { return (int) TotalGrade; } public int getUsualGrade() { return 0; } public int getFinalGrade() { return 0; } } class ExamGrade extends Grade{ int UsualGrade; int FinalGrade; public int getTotalGrade(){ return (int)(0.3*this.getUsualGrade()+0.7*this.getFinalGrade()); } public int getUsualGrade() { return UsualGrade; } public void setUsualGrade(int usualGrade) { UsualGrade = usualGrade; } public int getFinalGrade() { return FinalGrade; } public void setFinalGrade(int finalGrade) { FinalGrade = finalGrade; } } class NoExamGrade extends Grade{ int FinalGrade; public int getTotalGrade(){ return FinalGrade; } public int getFinalGrade() { return FinalGrade; } public void setFinalGrade(int finalGrade) { FinalGrade = finalGrade; } } class Student{ String num; String name; public Student(String num, String name) { this.num = num; this.name = name; } public String getNum() { return num; } public String getName() { return name; } } class Course{ String name; String kind; String method; public Course(String name, String kind, String method) { this.name = name; this.kind = kind; this.method = method; } public String getName() { return name; } public String getMethod() { return method; } } class SelectCourse{ Course course; Student student; Grade grade; public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; } } class InputMatching { static String scoreMatching = "(\\d|[1-9]\\d|100)"; static String courseNameMatching = "\\S{1,10}"; static String stuNumMatching = "[0-9]{8}"; static String stuNameMatching = "\\S{1,10}"; static String courseTypeMatching = "(选修|必修|实验)"; static String checkcourseTypeMatching = "(考试|考察|实验)"; static String courseInput = courseNameMatching + " " + courseTypeMatching + " " + checkcourseTypeMatching; static String scoreInput = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " + scoreMatching + "(\\s"+scoreMatching+")*"; 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); } }
PTA第八次题目集主要由五道小题,容器arraylist排序,身份证排序,接口以及覆盖,和课程成绩统计程序3
容器arraylist排序,身份证排序,接口以及覆盖这几道小题主要是对java的基础知识语法的应用,看起来比较简单但我还是不会,
ArrayList容器特征:用数组实现存储,查询效率高,增删效率低,线程不安全
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); List<Student> students = new ArrayList<>(); while (sc.hasNextLine()) { String line = sc.nextLine().trim(); if ("end".equals(line)) { break; } else { String[] arr = line.split("\\s+"); Student student = new Student(arr[0], arr[1], Integer.parseInt(arr[2]), Integer.parseInt(arr[3])); students.add(student); } } Collections.sort(students, (a, b) -> { int abSum = a.ma + a.phy; int bbSum = b.ma + b.phy; if (abSum != bbSum) { return bbSum - abSum; } else { return students.indexOf(a) - students.indexOf(b); } }); for (Student student : students) { System.out.println(String.format("%s %s %d", student.num, student.name, student.ma+ student.phy)); } } static class Student { int ma; int phy; String num; String name; public Student(String num, String name, int ma, int phy) { this.num = num; this.name = name; this.ma = ma; this.phy = phy; } } }
7-4 jmu-Java-04面向对象进阶-03-接口-自定义接口ArrayIntegerStack
定义IntegerStack接口,用于声明一个存放Integer元素的栈的常见方法:
定义IntegerStack的实现类ArrayIntegerStack,内部使用数组实现。创建时,可指定内部数组大小。
import java.util.Arrays; import java.util.Scanner; interface IntegerStack{ public Integer push(Integer item); public Integer pop(); public Integer peek(); public boolean empty(); public int size(); } class ArrayIntegerStack implements IntegerStack{ private int a[]; private int end=0; public ArrayIntegerStack(int num) { a=new int[num]; } public Integer push(Integer item) { if (item==null){ return null; } if (end==a.length){ return null; } a[end]=item; end++; return item; } public int size() { return end; } public Integer pop() { if (end==0){ return null; } end--; return a[end]; } public boolean empty() { if (end==0){ return true; } return false; } public Integer peek() { if (end==0){ return null; } return a[end-1]; } public String toString() { String s=""; int i=0; while (i<end-1){ s+=a[i]+", "; i++; } if (end==0){ while (i<a.length-1){ s+="null, "; i++; } s+="null"; }else { if (end<a.length){ s+=a[i]+", "; for (int p=0;p<a.length-end-1;p++){ s+="null, "; } s+=null; }else { s+=a[i]; } } return "["+s+"]"; } } public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); ArrayIntegerStack arrayIntegerStack = new ArrayIntegerStack(sc.nextInt()); int num=sc.nextInt(); for(int i=0;i<num;i++){ System.out.println(arrayIntegerStack.push(sc.nextInt())); } System.out.println(arrayIntegerStack.peek()+","+arrayIntegerStack.empty()+","+arrayIntegerStack.size()); String arr=arrayIntegerStack.toString(); System.out.println(arrayIntegerStack.toString()); int time=sc.nextInt(); for (int i=0;i<time;i++){ System.out.println(arrayIntegerStack.pop()); } System.out.println(arrayIntegerStack.peek()+","+arrayIntegerStack.empty()+","+arrayIntegerStack.size()); System.out.println(arr); } }
7-5 jmu-Java-03面向对象基础-05-覆盖
Java每个对象都继承自Object,都有equals、toString等方法。现在需要定义
PersonOverride
类并覆盖其toString
与equals
方法。
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); } }
课程成绩统计程序3
课程成绩统计程序-3在第二次的基础上修改了计算总成绩的方式,
要求:修改类结构,将成绩类的继承关系改为组合关系,成绩信息由课程成绩类和分项成绩类组成,课程成绩类组合分项成绩类,分项成绩类由成绩分值和权重两个属性构成。
完成课程成绩统计程序-2、3两次程序后,比较继承和组合关系的区别。思考一下哪一种关系运用上更灵活,更能够适应变更。
题目最后的参考类图未做修改,大家根据要求自行调整,以下内容加粗字体显示的内容为本次新增的内容。
某高校课程从性质上分为:必修课、选修课、实验课,从考核方式上分为:考试、考察、实验。
考试的总成绩由平时成绩、期末成绩分别乘以权重值得出,比如平时成绩权重0.3,期末成绩权重0.7,总成绩=平时成绩*0.3+期末成绩*0.7。
考察的总成绩直接等于期末成绩
实验的总成绩等于课程每次实验成绩乘以权重后累加而得。
课程权重值在录入课程信息时输入。(注意:所有分项成绩的权重之和应当等于1)
必修课的考核方式必须为考试,选修课可以选择考试、考察任一考核方式。实验课的成绩必须为实验。
1、输入:
包括课程、课程成绩两类信息。
课程信息包括:课程名称、课程性质、考核方式、分项成绩数量、每个分项成绩的权重。
考试课信息格式:课程名称+英文空格+课程性质+英文空格+考核方式+英文空格+平时成绩的权重+英文空格+期末成绩的权重
考察课信息格式:课程名称+英文空格+课程性质+英文空格+考核方式
实验课程信息格式:课程名称+英文空格+课程性质+英文空格+考核方式+英文空格+分项成绩数量n+英文空格+分项成绩1的权重+英文空格+。。。+英文空格+分项成绩n的权重
实验次数至少4次,不超过9次
课程性质输入项:必修、选修、实验
考核方式输入选项:考试、考察、实验
考试/考查课程成绩信息包括:学号、姓名、课程名称、平时成绩(可选)、期末成绩
考试/考查课程成绩信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+平时成绩+英文空格+期末成绩
实验课程成绩信息包括:学号、姓名、课程名称、每次成绩{在系列-2的基础上去掉了(实验次数),实验次数要和实验课程信息中输入的分项成绩数量保持一致}
实验课程信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+第一次实验成绩+...+英文空格+最后一次实验成绩
以上信息的相关约束:
1)成绩是整数,不包含小数部分,成绩的取值范围是【0,100】
2)学号由8位数字组成
3)姓名不超过10个字符
4)课程名称不超过10个字符
5)不特别输入班级信息,班级号是学号的前6位。
2、输出:
输出包含三个部分,包括学生所有课程总成绩的平均分、单门课程总成绩平均分、班级所有课程总成绩平均分。
为避免四舍五入误差,
计算单个成绩时,分项成绩乘以权重后要保留小数位,计算总成绩时,累加所有分项成绩的权重分以后,再去掉小数位。
学生总成绩/整个班/课程平均分的计算方法为累加所有符合条件的单个成绩,最后除以总数。
1)学生课程总成绩平均分按学号由低到高排序输出
格式:学号+英文空格+姓名+英文空格+总成绩平均分
如果某个学生没有任何成绩信息,输出:学号+英文空格+姓名+英文空格+"did not take any exams"
2)单门课程成绩按课程名称的字符顺序输出
课程成绩输出格式:课程名称+英文空格+总成绩平均分
如果某门课程没有任何成绩信息,输出:课程名称+英文空格+"has no grades yet"
3)班级所有课程总成绩平均分按班级由低到高排序输出
格式:班级号+英文空格+总成绩平均分
如果某个班级没有任何成绩信息,输出:班级名称+英文空格+ "has no grades yet"
异常情况:
1)如果解析某个成绩信息时,课程名称不在已输入的课程列表中,输出:学号+英文空格+姓名+英文空格+":"+课程名称+英文空格+"does not exist"
2)如果解析某个成绩信息时,输入的成绩数量和课程的考核方式不匹配,输出:学号+英文空格+姓名+英文空格+": access mode mismatch"
以上两种情况如果同时出现,按第一种情况输出结果。
3)如果解析某个课程信息时,输入的课程性质和课程的考核方式不匹配,输出:课程名称+" : course type & access mode mismatch"
4)格式错误以及其他信息异常如成绩超出范围等,均按格式错误处理,输出"wrong format"
5)若出现重复的课程/成绩信息,只保留第一个课程信息,忽略后面输入的。
6)如果解析实验课程信息时,输入的分项成绩数量值和分项成绩权重的个数不匹配,输出:课程名称+" : number of scores does not match"
7)如果解析考试课、实验课时,分项成绩权重值的总和不等于1,输出:课程名称+" : weight value error"
信息约束:
1)成绩平均分只取整数部分,小数部分丢弃
import java.util.*; import java.text.*; class Calculate_grades { int stu_all_grades(Data_storage data_storage,String num){//单个学生总课程平均分计算 返回一个分数 1) int count =0;//这个学生有几门课 int sum = 0; for (Map.Entry<String, Score> entry : data_storage.stu__st_cour.get(num).gradeMap.entrySet()) { Score value = entry.getValue(); if(Integer.parseInt(value.total_scores)>=0) { count++; sum += Integer.parseInt(value.total_scores); } } if(count!=0) return sum/count; else return -100;//没有参加任何考试 } int[] single_course_grades(Data_storage data_storage,String name){ //2) 课程名 int count = 0; int[] aver_grade = new int[3];//0:平时成绩 1:期末考试 2:总分平均 for (Map.Entry<String, StudentsAll_mes> e : data_storage.stu__st_cour.entrySet()) {//遍历选课类:num-选课类 StudentsAll_mes value = e.getValue(); for (Map.Entry<String, Score> entry : value.gradeMap.entrySet()) {//遍历选课类:course.name-Score String key1 = entry.getKey(); Score value1 = entry.getValue(); if (key1.equals(name)) { if(Integer.parseInt(value1.total_scores)>=0) {//总分为- 说明算成绩无效 count++; aver_grade[2] += Integer.parseInt(value1.total_scores); if (value1 instanceof Test_Score) { if (Integer.parseInt(value1.total_scores) >= 0) { aver_grade[0] += Integer.parseInt(((Test_Score) value1).normal_score); aver_grade[1] += Integer.parseInt(((Test_Score) value1).end_score); } } else if (value1 instanceof Inspect_Score){ if (Integer.parseInt(value1.total_scores) >= 0) { aver_grade[0] = -100;//不需要平时成绩 aver_grade[1] += Integer.parseInt(((Inspect_Score) value1).end_score); } }else if(value1 instanceof Lab_Score){ if(Integer.parseInt(value1.total_scores)>=0){ aver_grade[0] = -100; aver_grade[1] += aver_grade[1] += Integer.parseInt(value1.total_scores); } } } } } } if(count!=0) { for (int i = 0; i < 3; i++) { aver_grade[i] = aver_grade[i] / count; } }else { for (int i = 0; i < 3; i++) { aver_grade[i] = -100; } } return aver_grade; } int Class_grades(Data_storage data_storage,String num){//3) int sum = 0; int count = 0; for (Map.Entry<String, Student> mapEntry : data_storage.classes.get(num).students.entrySet()) {//班级号-Student类 Student value = mapEntry.getValue();//遍历这个班级的所有学生 for (Map.Entry<String, StudentsAll_mes> e : data_storage.stu__st_cour.entrySet()) {//stu_num-选课类 String key1 = e.getKey();//遍历学生的选课类 学号 StudentsAll_mes value1 = e.getValue(); if (key1.equals(value.num)) {//选课类中 跟输入的学号一样 for (Map.Entry<String, Score> entry : value1.gradeMap.entrySet()) {//该num所有成绩遍历 Score gra = entry.getValue(); if(Integer.parseInt(gra.total_scores)>=0) {//有效才算 sum += Integer.parseInt(gra.total_scores); count++; } } } } } if(count!=0) return sum/count; else return -100; } void final_score(Data_storage data_storage,String num){//计算没门课的成绩 学号 data_storage.stu__st_cour.get(num).gradeMap.forEach((key,value)->{//学号 成绩 if(value instanceof Test_Score&&((Test_Score) value).normal_score.matches("\\d+")&&((Test_Score) value).end_score.matches("\\d+")) { double tem = ((Test_Course) data_storage.courses.get(key)).normal_weight*Integer.parseInt(((Test_Score) value).normal_score); double tem1 = ((Test_Course) data_storage.courses.get(key)).end_weight*Integer.parseInt(((Test_Score) value).end_score); value.total_scores = String.valueOf((int)(tem+tem1)); }else if(value instanceof Inspect_Score&&((Inspect_Score) value).end_score.matches("\\d+")){ value.total_scores = ((Inspect_Score) value).end_score; }else if(value instanceof Lab_Score&&((Lab_Score) value).lab_num.matches("\\d+")){ float sum = 0; int i=0; for (Integer score : ((Lab_Score) value).scores) { sum+= score* ((Lab_Course) data_storage.courses.get(key)).weights.get(i); i++; } value.total_scores = String.valueOf((int)sum); } }); } } class Class { String num; TreeMap<String, Student> students = new TreeMap<>(); //班级里的学生 学号 学生 Class(String num){ this.num = num; } } class Course { String type; String test_way; String name; Course(String name,String type, String test_way){ this.type = type; this.name = name; this.test_way = test_way; } } class Inspect_Course extends Course{ Inspect_Course(String name, String type, String test_way) { super(name, type, test_way); } } class Test_Course extends Course{ double normal_weight; double end_weight; Test_Course(String name, String type, String test_way,String normal_weight,String end_weight) { super(name, type, test_way); this.normal_weight = Float.parseFloat(normal_weight); this.end_weight = Float.parseFloat(end_weight); } } class Lab_Course extends Course{ int sub_scores_num; ArrayList<Float> weights = new ArrayList<>(); Lab_Course(String name, String type, String test_way,String line) { super(name, type, test_way); String[] lines = line.split(" "); sub_scores_num = Integer.parseInt(lines[3]); for(int i=4;i<lines.length; i++){ weights.add(Float.parseFloat(lines[i])); } } } class Data_storage { TreeMap<String , Course> courses;//课程 k:课程名 v:课程 TreeMap<String, Class> classes = new TreeMap<>();//班级 k:班级号V:班级 TreeMap<String, StudentsAll_mes> stu__st_cour;//选课类学生类结合 k:学号 v:选课类 InAndOut_put output = new InAndOut_put(); Data_storage(){ //学生和选课类结合 stu__st_cour = new TreeMap<>(Data_storage::compare);//重写排序 courses = new TreeMap<>(Data_storage::compare); } private static int compare(String o1, String o2) { try { Comparator<Object> comparator = Collator.getInstance(Locale.CHINA); if (comparator.compare(o1, o2) < 0) { return -1; } else if (comparator.compare(o1, o2) > 0) { return 1; } } catch (Exception ignored) { } return 0; } void setInspectCourses(String name, String type, String test_way){ if(!courses.containsKey(name)) { courses.put(name, new Inspect_Course(name, type, test_way)); } } void setTestCourses(String name, String type, String test_way,String normal_weight, String end_weight){ if(!courses.containsKey(name)) { courses.put(name, new Test_Course(name, type, test_way,normal_weight, end_weight)); } } void setLabCourses(String name, String type, String test_way,String line){ if(!courses.containsKey(name)) { courses.put(name, new Lab_Course(name, type, test_way,line)); } } void setClasses(String num){ if(!classes.containsKey(num)) { classes.put(num, new Class(num)); } } void setStudents(String clas_num, String name, String num){//班级号 姓名 学号 if(classes.containsKey(clas_num)){ if(!classes.get(clas_num).students.containsKey(num)) classes.get(clas_num).students.put(num,new Student(name,num)); } } void setStu__st_courAndMap(String num,String course,String normal_score,String end_score){//添加选课类 学生姓名 课程名称 分数 if(!stu__st_cour.containsKey(num)){ stu__st_cour.put(num,new StudentsAll_mes(num,course,normal_score,end_score)); } else{ stu__st_cour.get(num).setGradeMap(course,normal_score,end_score); } } void setStu__st_courAndMap(String num,String course,String end_score){ if(!stu__st_cour.containsKey(num)){ stu__st_cour.put(num,new StudentsAll_mes(num,course,end_score)); } else{ stu__st_cour.get(num).setGradeMap(course,end_score); } } void set_lab_grades(String stu_num,String course,String lab_num,String grades){ ArrayList<Integer> scores = new ArrayList<>(); String[] tem = grades.split(" "); for(int i=3;i<tem.length;i++){ if(tem[i].matches("\\d+")) scores.add(Integer.parseInt(tem[i])); } if(!stu__st_cour.containsKey(stu_num)){ StudentsAll_mes tem_stu_mes = new StudentsAll_mes(); tem_stu_mes.set_lab_stu_mes(stu_num,course,lab_num,scores); stu__st_cour.put(stu_num,tem_stu_mes); }else{ stu__st_cour.get(stu_num).set_lab_gradeMap(course,lab_num,scores); } } } class Input_Format { String regex_c_test = "^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s(必修|选修)\\s考试\\s((0.\\d{1,2})|(1-9?))\\s((0.\\d{1,2})|(1-9?))$"; String regex_c_inspect = "[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s选修\\s考察$"; String regex_c_lab = "^[\\u4e00-\\u9fa5a-zA-Z0-9 ]{1,10}\\s实验\\s实验\\s[4-9]\\s((0.\\d{1,2})|(1-9?))(\\s((0.\\d{1,2})|(1-9?))){3,9}$"; String regex_CS = "^\\d{8}\\s+[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s+[\\u4E00-\\u9FA5A-Za-z0-9]{1,10}\\s*((100)|(\\d{1,2})|(0))?\\s+((100)|(\\d{1,2})|(0))$"; String regex_lab = "^\\d{8}\\s[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s[\\u4e00-\\u9fa5a-zA-Z0-9 ]{1,10}\\s((100)|([1-9]\\d)|\\d)(\\s((100)|([1-9]\\d)|\\d)){2,9}$"; boolean isEnd = true;//结束标志 String[] strings; void inputProcessing(String line,Data_storage data_storage) { lineProcessing(line);//分割 data_storage.output.add_input(line);//存储 if(line.matches(regex_c_inspect)){ data_storage.setInspectCourses(strings[0],strings[1],strings[2]); }else if(line.matches(regex_c_lab)){ data_storage.setLabCourses(strings[0],strings[1],strings[2],line); }else if(line.matches(regex_c_test)){ data_storage.setTestCourses(strings[0],strings[1],strings[2],strings[3],strings[4]);//成绩信息 } else if(line.matches(regex_CS)||line.matches(regex_lab)){ data_storage.setClasses(strings[0].substring(0,6)); data_storage.setStudents(strings[0].substring(0, 6), strings[1], strings[0]);//学生的添加 if (data_storage.courses.containsKey(strings[2])) {//课程里有这个课 if (data_storage.courses.get(strings[2]).type.equals("选修")) {// if (data_storage.courses.get(strings[2]).test_way.equals("考试")&&strings.length == 5) { data_storage.setStu__st_courAndMap(strings[0], strings[2], strings[3], strings[4]); }else if(data_storage.courses.get(strings[2]).test_way.equals("考察")&&strings.length==4){ data_storage.setStu__st_courAndMap(strings[0], strings[2], strings[3]); } else { data_storage.setStu__st_courAndMap(strings[0], strings[2], "no access", "no access"); } } else if (data_storage.courses.get(strings[2]).type.equals("必修")) {// if (strings.length == 5) { data_storage.setStu__st_courAndMap(strings[0], strings[2], strings[3],strings[4]); } else {//无效 data_storage.setStu__st_courAndMap(strings[0], strings[2], "no access", "no access"); } } else if(data_storage.courses.get(strings[2]).type.equals("实验")){ if(strings.length == 3+((Lab_Course) data_storage.courses.get(strings[2])).sub_scores_num){ data_storage.set_lab_grades(strings[0],strings[2], String.valueOf(((Lab_Course) data_storage.courses.get(strings[2])).sub_scores_num),line); }else{ data_storage.set_lab_grades(strings[0],strings[2],"num error","no access"); } } }else{ data_storage.setStu__st_courAndMap(strings[0], strings[2], "not exist"); } } } void lineProcessing(String line){ strings = line.split(" "); } } class Inspect_Score extends Score{ String end_score; Inspect_Score(String end_score) { this.end_score = end_score; } } class Output_Format { Calculate_grades calculate = new Calculate_grades(); String regex_c_test = "^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s(必修|选修|实验)\\s(考试|考察|实验)\\s((\\d{1,2})|(1-9?))\\s((\\d{1,2})|(1-9?))$"; String regex_c_test_e = "^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s(必修|选修|实验)\\s(考试|考察|实验)\\s((0.\\d{1,2})|(1-9?))\\s((0.\\d{1,2})|(1-9?))$"; String regex_c_inspect = "[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s(必修|选修|实验)\\s(考试|考察|实验)$"; String regex_c_lab = "^[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s(必修|选修|实验)\\s(考试|考察|实验)\\s[4-9]\\s((0.\\d{1,2})|(1-9?))(\\s((0.\\d{1,2})|(1-9?))){1,10}$"; String regex_CS = "^\\d{8}\\s+[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s+[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s*((100)|(\\d{1,2})|(0))?\\s+((100)|(\\d{1,2})|(0))$"; String regex_lab = "^\\d{8}\\s[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s[\\u4e00-\\u9fa5a-zA-Z0-9]{1,10}\\s((100)|([1-9]\\d)|\\d)(\\s((100)|([1-9]\\d)|\\d)){1,20}$"; void outputProcessing(Data_storage data) { data.classes.forEach((num,Class)-> Class.students.forEach((name, student)-> calculate.final_score(data,student.num))); for(String i:data.output.input){ String[] tem = i.split(" "); if(i.matches(regex_c_test_e)||i.matches(regex_c_test)||i.matches(regex_c_inspect)||i.matches(regex_c_lab)){ if(tem[1].equals("必修")&&(tem[2].equals("考察")||tem[2].equals("实验"))){ data.output.add_output(tem[0] + " : course type & access mode mismatch"); }else if(tem[1].equals("实验")&&!tem[2].equals("实验")) { data.output.add_output(tem[0] + " : course type & access mode mismatch"); }else if(tem[1].equals("选修")&&tem[2].equals("实验")) { data.output.add_output(tem[0] + " : course type & access mode mismatch"); } if(tem[1].equals("实验")&&tem[2].equals("实验")) { if(tem.length-4>=4&&tem.length - 4<=9) { if (Integer.parseInt(tem[3]) != tem.length - 4) { data.output.add_output(tem[0] + " : number of scores does not match"); data.courses.remove(tem[0]); continue; } float tem_weight = 0; for (int j = 4; j < tem.length; j++) { tem_weight += Float.parseFloat(tem[j]); } if (Math.abs(tem_weight - 1) > 0.0001) { data.output.add_output(tem[0] + " : weight value error"); data.courses.remove(tem[0]); continue; } }else{ try { if (Integer.parseInt(tem[3]) != tem.length - 4) { data.output.add_output(tem[0] + " : number of scores does not match"); data.courses.remove(tem[0]); continue; } } catch (Exception ignored) { } } }if((tem[1].equals("必修")||tem[1].equals("选修"))&&tem[2].equals("考试")){ if(tem.length-3==2) { float tem_weight = Float.parseFloat(tem[3]) + Float.parseFloat(tem[4]); if (Math.abs(tem_weight - 1) > 0.0001) { data.output.add_output(tem[0] + " : weight value error"); data.courses.remove(tem[0]); } } } }else if(i.matches(regex_CS)||i.matches(regex_lab)) { if(!data.courses.containsKey(tem[2])){//不存在 data.output.add_output(tem[2]+" does not exist"); data.stu__st_cour.get(tem[0]).gradeMap.remove(tem[2]); }else{ if(data.courses.get(tem[2]).type.equals("必修") && tem.length!=5) {//必修 但是只有期末成绩 data.output.add_output(tem[0]+" "+tem[1]+" : access mode mismatch"); }else if(data.courses.get(tem[2]).type.equals("选修")) { if ((data.courses.get(tem[2]).test_way.equals("考试") && tem.length != 5) || (data.courses.get(tem[2]).test_way.equals("考察") && tem.length != 4)) data.output.add_output(tem[0] + " " + tem[1] + " : access mode mismatch"); }else if(data.courses.get(tem[2]).type.equals("实验")){ if(data.courses.get(tem[2]).test_way.equals("实验")&&(tem.length-3<4||tem.length-3>9||tem.length-3!=((Lab_Course) data.courses.get(tem[2])).sub_scores_num)) data.output.add_output(tem[0] + " " + tem[1] + " : access mode mismatch"); } } }else if(!i.equals("end")){ data.output.add_output("wrong format"); } } data.classes.forEach((cla_num,Class1)->{//遍历所有班级 Class1.students.forEach((stu_num,student)->{ int tem=calculate.stu_all_grades(data,stu_num); if(tem>=0) data.output.add_output(stu_num+" "+Class1.students.get(stu_num).name+" "+tem); else data.output.add_output(stu_num+" "+Class1.students.get(stu_num).name+" "+"did not take any exams"); }); }); data.courses.forEach((key,value)-> { int[] tem = calculate.single_course_grades(data, key); if (tem[0] < 0 && tem[1] < 0 && tem[2] < 0) {//三个为- 则没成绩 data.output.add_output(key + " has no grades yet"); }else { if (value.type.equals("选修") || value.type.equals("必修") || value.type.equals("实验")) { data.output.add_output(key + " " + tem[2]); } } }); data.classes.forEach((num,Class)->{ int tem = calculate.Class_grades(data,num); if(tem>=0) { data.output.add_output(num + " " + tem); }else data.output.add_output(num+" has no grades yet"); }); } void output_all(Data_storage data){ data.output.output.forEach(System.out::println); } } abstract class Score { String total_scores = "-100"; } class Student { String name; String num; Student(String name, String num) { this.name = name; this.num = num; } } class StudentsAll_mes { String num;//学生 TreeMap<String,Score> gradeMap =new TreeMap<>(); StudentsAll_mes(String stu_name, String course, String normal_score,String test_score){ this.num = stu_name; gradeMap.put(course,new Test_Score(normal_score,test_score)); } StudentsAll_mes(String stu_name, String course, String test_score){ this.num = stu_name; gradeMap.put(course,new Inspect_Score(test_score)); } public StudentsAll_mes() { } void set_lab_stu_mes(String stu_num,String course,String lab_num,ArrayList<Integer> scores){ this.num = stu_num; gradeMap.put(course,new Lab_Score(lab_num,scores)); } void set_lab_gradeMap(String course,String lab_num,ArrayList<Integer> scores){ if(!gradeMap.containsKey(course)) gradeMap.put(course,new Lab_Score(lab_num,scores)); } void setGradeMap(String course, String normal_score,String test_score){ if(!gradeMap.containsKey(course)) gradeMap.put(course, new Test_Score(normal_score,test_score)); } void setGradeMap(String course,String test_score){ if(!gradeMap.containsKey(course)) gradeMap.put(course,new Inspect_Score(test_score)); } } class Test_Score extends Score{ String normal_score; String end_score; Test_Score(String normal_score,String end_score) { this.normal_score = normal_score; this.end_score = end_score; } } class Lab_Score extends Score { String lab_num;//试验次数 ArrayList<Integer> scores; Lab_Score(String lab_num,ArrayList<Integer> scores){ this.lab_num = lab_num; this.scores = scores; } } class InAndOut_put { List<String> output = new ArrayList<>(); List<String> input = new ArrayList<>(); void add_output(String out){ output.add(out); } void add_input(String out){ input.add(out); } } public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Input_Format inputFormat = new Input_Format();//输入 Output_Format outputFormat = new Output_Format();//输出 Data_storage data_storage = new Data_storage(); while (inputFormat.isEnd){ String inputLine = scanner.nextLine(); if(inputLine.equals("end")){ inputFormat.isEnd = false; break; } inputFormat.inputProcessing(inputLine,data_storage); } outputFormat.outputProcessing(data_storage); outputFormat.output_all(data_storage); } }
期末考试的题目类似于期中考试的题目,前面选择题主要是java基础语法的知识这些看视频书籍可以学会大部分,后面的四道大题主要用到java的多态和接口,但是掌握的不好考试也没写出来,就不附上代码了。
总结:
本学期的Java课程就接近尾声了,单个人感觉掌握的都不是很好,主要原因可能还是自己练习的太少,希望以后自己勤快点多加练习,java的学习也让我们学到了新的语言新的东西。
标签:return,tem,name,BLOG,num,public,String From: https://www.cnblogs.com/GuazhuEastRoad/p/17888744.html