前言
这次的题目集总共有三道题,难度逐级增加,不过只要逻辑清晰,还是很容易做出来的。
以下是涉及到的知识点:
-
Java基础语法,包括变量、数据类型、运算符、控制语句等。
-
Java中的字符串处理,包括字符串的拼接、分割、替换等。
-
Java中的数组和集合,包括数组的定义、初始化、遍历等,以及集合的定义、添加元素、遍历等。
-
Java中的异常处理机制,包括try-catch语句、throw语句等。
-
Java中的排序算法,包括冒泡排序、选择排序、插入排序等。
-
Java中的面向对象编程,包括类的定义、继承、封装、多态等。
设计与分析
题目集6:
先给出我的代码
1 import java.text.Collator; 2 import java.util.*; 3 4 public class Main { 5 public static void main(String args[]) { 6 ArrayList<Student> students = new ArrayList<Student>();// 创建学生List储存每条分数记录来输出每个学生总成绩平均分 7 ArrayList<Curriculum> curriculums = new ArrayList<Curriculum>();// 同前 8 ArrayList<Class> classes = new ArrayList<Class>();// 同前 9 Scanner input = new Scanner(System.in); 10 String in = input.nextLine(); 11 while (!in.equals("end")) { 12 Student student = new Student();// 防止一址变则全变 13 Curriculum curriculum = new Curriculum(); 14 switch (InputMatching.matchingInput(in)) { 15 case 1: { 16 curriculum.getCourseMessage(in); 17 if (searchCurriculums(curriculums, curriculum)) { 18 break; 19 } 20 curriculums.add(curriculum); 21 break; 22 } 23 case 2: { 24 student.getStudent(in); 25 if (searchCurriculum(curriculums, student.course.courseName) != null) { 26 student.course = searchCurriculum(curriculums, student.course.courseName);// 拿到学生课程的完整信息 27 } else { 28 System.out.println(student.course.courseName + " does not exist"); 29 } 30 student.getStuGrade(in);// 获取学生成绩 31 if (searchStudents(students, student)) { 32 break; 33 } 34 students.add(student); 35 break; 36 } 37 case 0: 38 System.out.println("wrong format"); 39 break; 40 } 41 in = input.nextLine(); 42 } 43 Collections.sort(curriculums); 44 Collections.sort(students); 45 for (int i = 0; i < curriculums.size(); i++) { 46 curriculums.get(i).getCourseStudent(students); 47 } 48 49 Class clazz = new Class(); 50 for (int i = 0; i < students.size(); i++) { 51 if (i == 0) { 52 clazz.getStuClass(students.get(i)); 53 if (students.size() == 1) { 54 classes.add(clazz); 55 break; 56 } 57 } 58 if ((i != 0 && !students.get(i).clazz.equals(students.get(i - 1).clazz))) { 59 classes.add(clazz); 60 clazz = new Class(); 61 clazz.getStuClass(students.get(i)); 62 } else if (i != 0) { 63 clazz.getStuClass(students.get(i)); 64 } 65 if (i == students.size() - 1) { 66 classes.add(clazz); 67 } 68 } 69 printGradeSummary(students); 70 for (int i = 0; i < curriculums.size(); i++) { 71 curriculums.get(i).getCourseGrade(); 72 } // 课程成绩输出 73 74 for (int i = 0; i < classes.size(); i++) { 75 classes.get(i).getCalssGrade(); 76 if (classes.get(i).classGrade != 0) { 77 System.out.println(classes.get(i).studentClass + " " 78 + (int) (classes.get(i).classGrade / (float) classes.get(i).students.size())); 79 } else { 80 System.out.println(classes.get(i).studentClass + " has no grades yet"); 81 } 82 } // 班级成绩输出 83 84 input.close(); 85 86 } 87 88 public static Curriculum searchCurriculum(ArrayList<Curriculum> curriculums, String courseName) { 89 for (Curriculum x : curriculums) { 90 if (x.courseName.equals(courseName) && x.property != null) { 91 return x; 92 } 93 } 94 return null; 95 } 96 97 public static boolean searchCurriculums(ArrayList<Curriculum> curriculums, Curriculum xCurriculum) { 98 for (Curriculum x : curriculums) { 99 if (x.courseName.equals(xCurriculum.courseName)) { 100 return true; 101 102 } 103 } 104 return false; 105 } 106 107 public static boolean searchStudents(ArrayList<Student> students, Student xStudent) { 108 for (Student x : students) { 109 if (x.studentNum.equals(xStudent.studentNum)) { 110 if (x.name.equals(xStudent.name)) { 111 if (x.course.courseName.equals(xStudent.course.courseName)) { 112 return true; 113 } 114 } 115 } 116 } 117 return false; 118 } 119 120 public static void printGradeSummary(List<Student> students) { 121 String currentStudentNum = ""; 122 int left = -1; 123 int right = -1; 124 125 for (Student student : students) { 126 if (!student.studentNum.equals(currentStudentNum)) { 127 if (left >= 0 && right >= 0) { 128 int cnt = right - left + 1; 129 int sum = 0; 130 for (int i = left; i <= right; i++) { 131 sum += students.get(i).grade.grade; 132 } 133 if (cnt == 1) { 134 if(sum!=0) 135 System.out.println(students.get(left).studentNum + " " + students.get(left).name 136 + " " + students.get(left).grade.grade); 137 else { 138 System.out.println(students.get(left).studentNum + " " + students.get(left).name 139 + " did not take any exams"); 140 } 141 } else if (sum > 0) { 142 int avg = (int) ((float) sum / cnt + 0.5); // 四舍五入取整 143 System.out.println(students.get(right).studentNum + " " + students.get(right).name 144 + " " + avg); 145 } else { 146 System.out.println(students.get(right).studentNum + " " + students.get(right).name 147 + " did not take any exams"); 148 } 149 } 150 currentStudentNum = student.studentNum; 151 left = right = students.indexOf(student); 152 } else { 153 right = students.indexOf(student); 154 } 155 } 156 157 // 处理最后一位学生 158 if (left >= 0 && right >= 0) { 159 int cnt = right - left + 1; 160 int sum = 0; 161 for (int i = left; i <= right; i++) { 162 sum += students.get(i).grade.grade; 163 } 164 if (cnt == 1) { 165 if (sum != 0) 166 System.out.println(students.get(left).studentNum + " " + students.get(left).name + " " 167 + students.get(left).grade.grade); 168 else 169 System.out.println(students.get(left).studentNum + " " + students.get(left).name + " " 170 + "did not take any exams"); 171 } else if (sum > 0) { 172 int avg = (int) ((float) sum / cnt + 0.5); // 四舍五入取整 173 System.out.println(students.get(right).studentNum + " " + students.get(right).name + " " 174 + avg); 175 } else { 176 System.out.println(students.get(right).studentNum + " " + students.get(right).name 177 + " did not take any exams"); 178 } 179 } 180 } 181 } 182 183 class InputMatching { 184 static String stuNumMatching = "[0-9]{8}";// 8个0-9的数字 185 static String stuNameMatching = "\\S{1,10}";// 1到10个非空格(TAB)字符 186 static String scoreMatching = "([1-9]?[0-9]|100)"; 187 static String courseNameMatching = "\\S{1,10}";// 1到10个非空格(TAB)字符 188 static String courseTypeMatching = "(选修|必修)"; 189 static String checkCourseTypeMatching = "(考试|考察)"; 190 // courseInput用于定义课程信息模式(正则表达式) 191 static String courseInput = courseNameMatching + " " + courseTypeMatching + " " + checkCourseTypeMatching; 192 // scoreInput用于定义成绩信息模式(正则表达式) 193 static String scoreInput1 = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " + scoreMatching 194 + " " + scoreMatching; 195 static String scoreInput2 = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " + scoreMatching; 196 197 public static int matchingInput(String s) { 198 if (matchingCourse(s)) { 199 return 1; 200 } 201 if (matchingScore(s)) { 202 return 2; 203 } 204 return 0; 205 } 206 207 private static boolean matchingCourse(String s) { 208 return s.matches(courseInput); 209 } 210 211 private static boolean matchingScore(String s) { 212 // System.out.println(match); 213 return s.matches(scoreInput1) || s.matches(scoreInput2); 214 } 215 } 216 217 class Class { 218 String studentClass; 219 ArrayList<Student> students = new ArrayList<Student>(); 220 int classGrade = 0; 221 222 public void getStuClass(Student student) { 223 if (students.size() == 0) { 224 students.add(student); 225 studentClass = student.clazz; 226 } else { 227 if (student.clazz.equals(studentClass)) { 228 students.add(student); 229 } 230 } 231 } 232 233 public void getCalssGrade() { 234 for (int i = 0; i < students.size(); i++) { 235 if (students.get(i).grade.grade != 0) { 236 classGrade += students.get(i).grade.grade; 237 } 238 } 239 } 240 } 241 242 class Student implements Comparable<Student> { 243 String name; 244 String clazz; 245 String studentNum; 246 Curriculum course = new Curriculum(); 247 Grade grade = new Grade(); 248 249 public void getStudent(String studentMessage) { 250 String s[] = studentMessage.split(" "); 251 studentNum = s[0]; 252 clazz = studentNum.substring(0, 6); 253 name = s[1]; 254 course.courseName = s[2]; 255 } 256 257 public void getStuGrade(String scoreMessage) { 258 grade.getGrade(scoreMessage, course, studentNum, name); 259 } 260 261 @Override 262 public int compareTo(Student stu) { 263 Comparator<Object> compare = Collator.getInstance(java.util.Locale.CHINA); 264 return compare.compare(this.studentNum, stu.studentNum); 265 } 266 267 } 268 269 class Grade { 270 int normalGrade = 0; 271 int finalGrade = 0; 272 int grade = 0; 273 274 public void getGrade(String scoreMessage, Curriculum curriculum, String studentNum, String name) { 275 if (curriculum.property == null) { 276 return; 277 } 278 String s[] = scoreMessage.split(" "); 279 if (curriculum.assessment.equals("考试")) { 280 if (s.length == 5) { 281 normalGrade = Integer.parseInt(s[3]); 282 finalGrade = Integer.parseInt(s[4]); 283 grade = (int) (finalGrade * 0.7 + normalGrade * 0.3); 284 } else { 285 System.out.println(studentNum + " " + name + " : access mode mismatch"); 286 } 287 } else if (curriculum.assessment.equals("考察")) { 288 if (s.length == 4) { 289 finalGrade = Integer.parseInt(s[3]); 290 grade = finalGrade; 291 } else 292 System.out.println(studentNum + " " + name + " : access mode mismatch"); 293 } else { 294 System.out.println(curriculum.courseName + " " + " : access mode mismatch"); 295 } 296 } 297 298 } 299 300 class Curriculum implements Comparable<Curriculum> { 301 ArrayList<Student> students = new ArrayList<Student>(); 302 String courseName; 303 String property; 304 String assessment; 305 ArrayList<Grade> grades = new ArrayList<Grade>(); 306 307 public void getCourseGrade() { 308 if (property == null) { 309 return; 310 } 311 int sum = 0; 312 if (assessment.equals("考察")) { 313 for (int i = 0; i < students.size(); i++) { 314 sum += students.get(i).grade.grade; 315 } 316 if (sum != 0) 317 System.out.println(courseName + " " + (int) (sum / (float) students.size()) + " " 318 + (int) (sum / (float) students.size())); 319 else 320 System.out.println(courseName + " has no grades yet"); 321 } else if (assessment.equals("考试")) { 322 int temp1 = 0; 323 int temp2 = 0; 324 for (int i = 0; i < students.size(); i++) { 325 temp1 += students.get(i).grade.normalGrade; 326 temp2 += students.get(i).grade.finalGrade; 327 sum += students.get(i).grade.grade; 328 } 329 if (sum != 0) 330 System.out.println(courseName + " " + (int) ((float) temp1 / students.size()) + " " 331 + (int) ((float) temp2 / students.size()) + " " + (int) ((float) sum / students.size())); 332 else 333 System.out.println(courseName + " has no grades yet"); 334 } else { 335 System.out.println(courseName + " has no grades yet"); 336 } 337 338 }// 记得用循环输出 每一个课程的都要输出一遍 339 340 public void getCourseStudent(ArrayList<Student> students) { 341 for (int i = 0; i < students.size(); i++) { 342 if (students.get(i).course.courseName.equals(courseName)) { 343 this.students.add(students.get(i)); 344 } 345 } 346 }// 也是要用循环 每一个课程都要添加一遍 347 348 public void getCourseMessage(String courseMessage) { 349 String s[] = courseMessage.split(" "); 350 if (s.length == 3) { 351 if (s[1].equals("必修")) { 352 if (s[2].equals("考试")) { 353 courseName = s[0]; 354 property = s[1]; 355 assessment = s[2]; 356 } else { 357 courseName = s[0]; 358 System.out.println(courseName + " : course type & access mode mismatch"); 359 } 360 } else if (s[1].equals("选修")) { 361 courseName = s[0]; 362 property = s[1]; 363 assessment = s[2]; 364 } 365 } else { 366 courseName = s[0]; 367 property = s[1]; 368 assessment = "考试"; 369 } 370 } 371 372 @Override 373 public int compareTo(Curriculum o) { 374 Comparator<Object> compare = Collator.getInstance(java.util.Locale.CHINA); 375 return compare.compare(courseName, o.courseName); 376 } 377 378 }
UML图如下:
InputMatching的类:
我在其中包含了一些静态变量和静态方法。这些变量和方法用于匹配输入的字符串是否符合特定的格式要求。
代码中定义了6个正则表达式,分别用于匹配学号、姓名、课程名称、成绩等信息的格式要求。其中,stuNumMatching用于匹配8个数字,stuNameMatching用于匹配1到10个非空格字符,scoreMatching用于匹配0到100之间的数字,courseNameMatching用于匹配1到10个非空格字符,courseTypeMatching用于匹配“选修”或“必修”,checkCourseTypeMatching用于匹配“考试”或“考察”。
在这段代码中,courseInput和scoreInput1/scoreInput2分别用于定义课程信息和成绩信息的模式。matchingInput方法用于判断输入的字符串是属于哪种类型(课程信息或成绩信息)。matchingCourse和matchingScore方法分别用于判断输入的字符串是否符合课程信息和成绩信息的格式要求。
Class类:
其中包含了三个成员变量和两个成员方法。这些变量和方法用于存储和计算班级的信息。
代码中,studentClass是一个字符串类型的变量,用于存储班级名称。students是一个ArrayList类型的变量,用于存储班级中的学生信息。classGrade是一个整型变量,用于存储班级的总成绩。
getStuClass方法用于将学生添加到班级中。如果班级中还没有学生,则将该学生添加到班级中,并将studentClass设置为该学生所在的班级名称;否则,如果该学生所在的班级名称与studentClass相同,则将该学生添加到班级中。
getCalssGrade方法用于计算班级的总成绩。它遍历students列表中的每个学生,如果该学生的成绩不为0,则将其成绩加到classGrade中。
Student类:
其中包含了五个成员变量和三个成员方法。这些变量和方法用于存储和处理学生的信息。
这段代码中,name、clazz、studentNum、course和grade分别是学生的姓名、班级名称、学号、课程信息和成绩信息。course和grade分别是Curriculum和Grade类型的对象,用于存储课程信息和成绩信息。
getStudent方法用于从输入的字符串中提取学生的信息。它首先将输入的字符串按空格分割成一个字符串数组s[],然后将s[0]赋值给studentNum,将studentNum的前6位赋值给clazz,将s[1]赋值给name,将s[2]赋值给course.courseName。
getStuGrade方法用于从输入的字符串中提取学生的成绩信息,并将其存储到grade对象中。它调用了grade对象的getGrade方法,该方法用于解析输入的字符串,并将解析后的成绩信息存储到grade对象中。
compareTo方法用于比较两个学生对象的大小。它实现了Comparable接口,并重写了compareTo方法。在该方法中,它使用了Collator类来比较两个学生对象的studentNum属性。
Grade类:
其中包含了三个成员变量和一个成员方法。这些变量和方法用于存储和计算学生的成绩信息。
这段代码中,normalGrade、finalGrade和grade分别是学生的平时成绩、期末成绩和总成绩。
getGrade方法用于从输入的字符串中提取学生的成绩信息,并将其存储到grade对象中。它首先判断课程的property属性是否为空,如果为空,则直接返回。然后,它将输入的字符串按空格分割成一个字符串数组s[],并根据课程的assessment属性来解析成绩信息。如果assessment属性为"考试",则需要解析平时成绩和期末成绩,并计算总成绩;如果assessment属性为"考察",则只需要解析期末成绩;否则,输出错误信息。
Curriculum类:
其中包含了四个成员变量和两个成员方法。这些变量和方法用于存储和处理课程信息和学生的成绩信息。
这段代码中,students、courseName、property、assessment和grades分别是学生列表、课程名称、课程属性、考核方式和成绩列表。
getCourseGrade方法用于计算并输出课程的平均成绩。它首先判断课程的property属性是否为空,如果为空,则直接返回。然后,根据课程的assessment属性来计算平均成绩。如果assessment属性为"考察",则需要计算所有学生的总成绩,并输出平均成绩;如果assessment属性为"考试",则需要计算所有学生的平时成绩、期末成绩和总成绩,并输出平均值;否则,输出错误信息。
getCourseStudent方法用于从输入的学生列表中提取该课程的学生信息,并将其存储到students列表中。
题目集7和8的代码
1 import java.util.*; 2 import java.text.Collator; 3 public class Main { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 String nextLine = input.nextLine(); 7 ParseInput handle=new ParseInput(); 8 while (!nextLine.equals("end")) { 9 handle.parseInput(nextLine);//解析用户输入的每一行数据 10 nextLine = input.nextLine(); 11 } 12 handle.showStudents(); 13 handle.showCourses(); 14 handle.showClasses(); 15 } 16 } 17 class ParseInput { 18 ArrayList<Course> courseList = new ArrayList<>(); 19 ArrayList<Student> studentList = new ArrayList<>(); 20 ArrayList<Slect> slectList = new ArrayList<>(); 21 ArrayList<Class> classList = new ArrayList<>(); 22 public void parseInput(String nextLine) { 23 String[] arraylist = nextLine.split(" "); 24 switch (InputMatching.matchingInput(nextLine)){ 25 case 1: 26 inputCourse(arraylist); 27 break; 28 case 2: 29 inputScore(arraylist); 30 break; 31 case 0: 32 System.out.println("wrong format"); 33 break; 34 } 35 } 36 37 Course getCourse(String courseName){ 38 for (Course course : courseList) { 39 if (course.getCourseName().equals(courseName)) 40 return course; 41 } 42 return null; 43 } 44 Class getclass(String classId){ 45 for (Class myClass : classList) { 46 if (myClass.getclassName().equals(classId)) 47 return myClass; 48 } 49 return null; 50 } 51 Student getStudent(String stuNum){ 52 for (Student student : studentList) { 53 if (student.getStuNumber().equals(stuNum)) 54 return student; 55 } 56 return null; 57 } 58 59 private void inputScore(String[] a){ 60 Class studentClass; 61 Student student; 62 studentClass=getclass(a[0].substring(0,6)); 63 if(studentClass==null){ 64 studentClass=new Class(a[0].substring(0,6)); 65 classList.add(studentClass); 66 } 67 student=getStudent(a[0]); 68 if(student==null){ 69 student=new Student(a[0], a[1]); 70 studentList.add(student); 71 studentClass.addStudent(student); 72 } 73 Course course=getCourse(a[2]); 74 if(course==null){ 75 System.out.println(a[2]+" does not exist"); 76 return; 77 } 78 if(!checkGrade(a,course)) 79 return; 80 Score score; 81 if(a.length==4){ 82 score=new classScore2(Integer.parseInt(a[3])); 83 } 84 else if(a.length==5) { 85 score=new classScore1(Integer.parseInt(a[3]),Integer.parseInt(a[4])); 86 } 87 else { 88 int num = Integer.parseInt(a[3]); 89 int [] aaa =new int[num]; 90 for (int i = 0; i < aaa.length; i++) { 91 aaa[i]=Integer.parseInt(a[i+4]); 92 } 93 score=new classScore3(aaa,0,num); 94 } 95 if(existSlectCourse(student,course)) return; 96 Slect slectCourse = new Slect(course, student, score); 97 slectList.add(slectCourse); 98 } 99 100 public void inputCourse(String[] a){ 101 Course course = new Course(a[0],a[1],a[2]); 102 if(!checkCourse(course)) 103 return; 104 if(getCourse(a[0])==null){ 105 course=new Course(a[0], a[1], a[2]); 106 courseList.add(course); 107 } 108 } 109 boolean checkCourse(Course course){ 110 if(course.getProperty().equals("必修")&&course.getAssessment().equals("考试")) 111 return true; 112 if(course.getProperty().equals("选修")&&course.getAssessment().equals("考试")) 113 return true; 114 if(course.getProperty().equals("选修")&&course.getAssessment().equals("考察")) 115 return true; 116 if(course.getProperty().equals("实验")&&course.getAssessment().equals("实验")) 117 return true; 118 System.out.println(course.getCourseName()+" : course type & access mode mismatch"); 119 return false; 120 } 121 122 boolean existSlectCourse(Student stu,Course course){ 123 for (Slect slect : slectList) { 124 if (slect.getCourse().getCourseName().equals(course.getCourseName())) { 125 if (slect.getStudent().getStuName().equals(stu.getStuName())) 126 return true; 127 } 128 } 129 return false; 130 } 131 private boolean checkGrade(String[] items,Course course){ 132 String courseType=course.getAssessment(); 133 if(courseType.equals("考试")&&items.length==5){ 134 return true; 135 } 136 if(courseType.equals("考察")&&items.length==4){ 137 return true; 138 } 139 if(courseType.equals("实验")&&items.length-4==Integer.parseInt(items[3])){ 140 return true; 141 } 142 System.out.println(items[0]+" "+items[1]+" : access mode mismatch"); 143 return false; 144 } 145 146 public static int getAvagScore1(ArrayList<Slect> courseSelects)//平时 147 { 148 int sum = 0; 149 for(Slect c : courseSelects) 150 { 151 sum +=((classScore1)(c.score)).getUsualScore(); 152 } 153 return sum/courseSelects.size(); 154 } 155 public int getFinalScore(ArrayList<Slect> courseSelects)//期末 156 { 157 int sum =0; 158 for(Slect c : courseSelects) 159 { 160 sum += c.score.getFinalScore(); 161 } 162 return sum/courseSelects.size(); 163 } 164 public int getTotalScore(ArrayList<Slect> listSlectCourse) 165 { 166 int sum =0; 167 for(Slect c : listSlectCourse) 168 { 169 sum +=c.score.getTotalScore(); 170 } 171 return sum/listSlectCourse.size(); 172 } 173 public int getScore(ArrayList<Slect> courseSelects)//实验 174 { 175 int sum =0; 176 for(Slect c : courseSelects) 177 { 178 sum +=c.score.getExperimentScore(); 179 } 180 return sum/courseSelects.size(); 181 } 182 183 public ArrayList<Slect> getStudentSelects(String stNumber) { 184 ArrayList<Slect> stus = new ArrayList<>(); 185 for (Slect slect : slectList) { 186 if (slect.student.getStuNumber().equals(stNumber)) { 187 stus.add(slect); 188 } 189 } 190 if(stus.size()!=0) 191 return stus; 192 else return null; 193 } 194 195 public ArrayList<Slect> getCourseSelects(String courseName){ 196 ArrayList<Slect> courses = new ArrayList<>(); 197 for (Slect slect : slectList) { 198 if (slect.course.getCourseName().equals(courseName)) { 199 courses.add(slect); 200 } 201 } 202 if(courses.size()!=0) 203 return courses; 204 else return null; 205 } 206 207 public ArrayList<Slect> getClassSelects(String classclassName){ 208 ArrayList<Slect> classes = new ArrayList<>(); 209 for (Slect slect : slectList) { 210 if (slect.student.getStuNumber().substring(0, 6).equals(classclassName)) { 211 classes.add(slect); 212 } 213 } 214 if(classes.size()!=0) 215 return classes; 216 else return null; 217 } 218 public void showStudents() { 219 Collections.sort(studentList); 220 for (Student student : studentList) { 221 ArrayList<Slect> stuCourseSelects = getStudentSelects(student.getStuNumber()); 222 //从总选课表Slect中获取该生的选课记录集合 223 if (stuCourseSelects != null) { 224 System.out.println(student.getStuNumber() + " " + student.getStuName() + " " + getTotalScore(stuCourseSelects)); 225 } else { 226 System.out.println(student.getStuNumber() + " " + student.getStuName() + " " + "did not take any exams"); 227 } 228 } 229 } 230 231 public void showCourses() { 232 Collections.sort(courseList); 233 for (Course course : courseList) { 234 ArrayList<Slect> CourseSelects = getCourseSelects(course.getCourseName()); 235 if (CourseSelects != null) { 236 if (course.getAssessment().equals("考试")) 237 System.out.println(course.getCourseName() + " " + getAvagScore1(CourseSelects) + " " + getFinalScore(CourseSelects) + " " + getTotalScore(CourseSelects)); 238 if (course.getAssessment().equals("考察")) 239 System.out.println(course.getCourseName() + " " + getFinalScore(CourseSelects) + " " + getTotalScore(CourseSelects)); 240 if (course.getAssessment().equals("实验")) 241 System.out.println(course.getCourseName() + " " + getScore(CourseSelects)); 242 } else { 243 System.out.println(course.getCourseName() + " has no grades yet"); 244 } 245 } 246 } 247 248 public void showClasses() { 249 Collections.sort(classList); 250 for (Class clazz : classList) { 251 ArrayList<Slect> stuClassSelects = getClassSelects(clazz.getclassName()); 252 if (stuClassSelects != null) { 253 System.out.println(clazz.getclassName() + " " + getTotalScore(stuClassSelects)); 254 } else { 255 System.out.println(clazz.getclassName() + " " + "has no grades yet"); 256 } 257 } 258 } 259 } 260 class Class implements Comparable<Class>{ 261 private final String className; 262 ArrayList<Student> listStudent=new ArrayList<>(); 263 264 public void addStudent(Student stu){ 265 listStudent.add(stu); 266 } 267 268 public Class(String className) { 269 this.className = className; 270 } 271 272 public String getclassName() { 273 return className; 274 } 275 276 @Override 277 public int compareTo(Class studentClass){ 278 return className.compareTo(studentClass.getclassName()); 279 } 280 } 281 class Slect { 282 Course course; 283 Student student; 284 Score score; 285 286 public Course getCourse() { 287 return course; 288 } 289 290 public Student getStudent() { 291 return student; 292 } 293 294 public Slect(Course course, Student student, Score score) { 295 this.course = course; 296 this.student = student; 297 this.score = score; 298 } 299 } 300 abstract class Score{ 301 public int finalScore;//期末 302 public int totalScore; 303 304 public int getTotalScore() { 305 return totalScore; 306 } 307 308 public int getFinalScore() { 309 return finalScore; 310 } 311 312 public int getExperimentScore() { 313 return totalScore; 314 } 315 316 Score(int finalScore) { 317 this.finalScore=finalScore; 318 } 319 } 320 class Student implements Comparable<Student>{ 321 private final String stuNum; 322 private final String name; 323 324 public Student(String stuNum, String name) { 325 this.name=name; 326 this.stuNum=stuNum; 327 } 328 329 public String getStuNumber() { 330 return stuNum; 331 } 332 333 public String getStuName() { 334 return name; 335 } 336 337 @Override 338 public int compareTo(Student student){ 339 return stuNum.compareTo(student.getStuNumber()); 340 } 341 }//储存学生数据的类 342 class InputMatching { 343 static String stuNumMatching = "[0-9]{8}";//8个0-9的数字 344 static String stuNameMatching = "\\S{1,10}";//1到10个非空格(TAB)字符 345 static String scoreMatching = "([1-9]?[0-9]|100)"; 346 static String scoreMatching1 = "([1-9]\\d?|0|100)( ([1-9]\\d?|0|100)){3,8}"; 347 static String courseNameMatching = "\\S{1,10}";//1到10个非空格(TAB)字符 348 static String coursePropertyMatching = "(选修|必修|实验)"; 349 static String courseAssessmentMatching = "(考试|考察|实验)"; 350 static String experimentNumber = "[4-9]"; 351 //courseInput用于定义课程信息模式(正则表达式) 352 static String courseInput = courseNameMatching + " " + coursePropertyMatching + " " + courseAssessmentMatching; 353 //scoreInput用于定义成绩信息模式(正则表达式) 354 static String scoreInput = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " + scoreMatching; 355 356 static String scoreInput1 = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " + scoreMatching + " "+scoreMatching; 357 static String scoreInput2 = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " + experimentNumber + " " +scoreMatching + " "+scoreMatching+ " "+scoreMatching; 358 static String scoreInput3 = stuNumMatching + " " + stuNameMatching + " " + courseNameMatching + " " + experimentNumber +" "+scoreMatching1; 359 public static int matchingInput(String s) { 360 if (matchingCourse(s)) { 361 return 1; 362 } 363 if (matchingScore(s)) { 364 return 2; 365 } 366 return 0; 367 } 368 369 static boolean matchingCourse(String string) { 370 return string.matches(courseInput); 371 } 372 static boolean matchingScore(String s) { 373 return (s.matches(scoreInput)||s.matches(scoreInput1)||s.matches(scoreInput2)||s.matches(scoreInput3)); 374 } 375 }//用于匹配输入模式的类 376 class Course implements Comparable<Course>{ 377 378 private final String courseName; 379 private final String property; 380 private final String assessment; 381 382 public Course(String courseName, String property, String assessment) { 383 this.courseName = courseName; 384 this.property = property; 385 this.assessment = assessment; 386 } 387 388 public String getCourseName() { 389 return courseName; 390 } 391 392 public String getProperty() { 393 return property; 394 } 395 396 public String getAssessment() { 397 return assessment; 398 } 399 400 @Override 401 public int compareTo(Course o) { 402 Comparator<Object> compare = Collator.getInstance(Locale.CHINA); 403 return compare.compare(courseName,o.getCourseName()); 404 } 405 } 406 class classScore1 extends Score{ 407 private final int Score1;//平时 408 409 public int getUsualScore() { 410 return Score1; 411 } 412 413 classScore1(int usualScore, int finalScore){ 414 super(finalScore); 415 this.Score1=usualScore; 416 this.totalScore=(int)(finalScore*0.7+usualScore*0.3); 417 } 418 } 419 class classScore2 extends Score{ 420 classScore2(int finalScore){ 421 super(finalScore); 422 this.totalScore=finalScore; 423 } 424 } 425 class classScore3 extends Score{ 426 classScore3(int[] experimentScore,int finalScore,int n){ 427 super(finalScore); 428 int sum=0; 429 for (int i = 0; i <n; i++) { 430 sum+=experimentScore[i]; 431 } 432 this.totalScore=sum/n; 433 } 434 }
这次的题目集的成绩题就是在原题上做出了一些小改动,只要稍稍改改原有代码就行。
1 import java.util.*; 2 import java.text.Collator; 3 import java.util.regex.Pattern; 4 5 public class Main { 6 public static void main(String[] args) { 7 Scanner input = new Scanner(System.in); 8 String nextLine = input.nextLine(); 9 ParseInput handle=new ParseInput(); 10 while (!nextLine.equals("end")) { 11 handle.parseInput(nextLine);//解析用户输入的每一行数据 12 nextLine = input.nextLine(); 13 } 14 handle.showStudents(); 15 handle.showCourses(); 16 handle.showClasses(); 17 } 18 } 19 class EnrollmentRecord { 20 private final Course course; 21 private final Student student; 22 private final Score score; 23 24 public EnrollmentRecord(Course course, Student student, Score score) { 25 this.course = course; 26 this.student = student; 27 this.score = score; 28 } 29 30 public Course getCourse() { 31 return course; 32 } 33 34 public Student getStudent() { 35 return student; 36 } 37 38 public Score getScore() { 39 return score; 40 } 41 } 42 class InputMatching { 43 private static final String STUDENT_NUMBER_REGEX = "[0-9]{8}"; 44 private static final String STUDENT_NAME_REGEX = "\\S{1,10}"; 45 private static final String SCORE_REGEX = "([1-9]?[0-9]|100)"; 46 private static final String COURSE_NAME_REGEX = "\\S{1,10}"; 47 private static final String COURSE_TYPE_REGEX = "(选修|必修)"; 48 private static final String CHECK_TYPE_REGEX = "(考试|考察|实验)"; 49 private static final String EXAM_SCORE_REGEX = "\\d+\\.\\d+"; 50 private static final String EXPERIMENT_NUMBER_REGEX = "[4-9]"; 51 private static final String SCORES_REGEX = SCORE_REGEX + "( " + SCORE_REGEX + "){0,9}"; 52 private static final Pattern COURSE_PATTERN = Pattern.compile(COURSE_NAME_REGEX + " " + COURSE_TYPE_REGEX + " " + CHECK_TYPE_REGEX); 53 private static final Pattern COURSE_PATTERN0 = Pattern.compile(COURSE_NAME_REGEX + " " + COURSE_TYPE_REGEX + " 考试 " + EXAM_SCORE_REGEX + " " + EXAM_SCORE_REGEX); 54 private static final Pattern COURSE_PATTERN1 = Pattern.compile(COURSE_NAME_REGEX + " 实验 实验 " + EXPERIMENT_NUMBER_REGEX + " " + EXAM_SCORE_REGEX + "( " + EXAM_SCORE_REGEX + "){2,9}"); 55 private static final Pattern SCORE_PATTERN = Pattern.compile(STUDENT_NUMBER_REGEX + " " + STUDENT_NAME_REGEX + " " + COURSE_NAME_REGEX + " " + SCORE_REGEX); 56 private static final Pattern SCORE_PATTERN1 = Pattern.compile(STUDENT_NUMBER_REGEX + " " + STUDENT_NAME_REGEX + " " + COURSE_NAME_REGEX + " " + SCORES_REGEX); 57 58 public static int matchingInput(String input) { 59 if (matchingCourse(input)) { 60 return 1; 61 } 62 if (matchingScore(input)) { 63 return 2; 64 } 65 return 0; 66 } 67 68 private static boolean matchingCourse(String input) { 69 return COURSE_PATTERN.matcher(input).matches() 70 || COURSE_PATTERN0.matcher(input).matches() 71 || COURSE_PATTERN1.matcher(input).matches(); 72 } 73 74 private static boolean matchingScore(String input) { 75 return SCORE_PATTERN.matcher(input).matches() || SCORE_PATTERN1.matcher(input).matches(); 76 } 77 } 78 79 80 class Course implements Comparable<Course> { 81 private final String name; 82 private final String description; 83 private final String examinationType; 84 private int courseNumber; 85 private double[] gradingWeights; 86 87 public Course(String name, String description, String examinationType, int courseNumber, double[] gradingWeights) { 88 this.name = name; 89 this.description = description; 90 this.examinationType = examinationType; 91 this.courseNumber = courseNumber; 92 this.gradingWeights = gradingWeights; 93 } 94 95 public Course(String name, String description, String examinationType, double[] gradingWeights) { 96 this.name = name; 97 this.description = description; 98 this.examinationType = examinationType; 99 this.gradingWeights = gradingWeights; 100 } 101 102 public Course(String name, String description, String examinationType) { 103 this.name = name; 104 this.description = description; 105 this.examinationType = examinationType; 106 } 107 108 public String getName() { 109 return name; 110 } 111 112 public String getDescription() { 113 return description; 114 } 115 116 public String getExaminationType() { 117 return examinationType; 118 } 119 120 public int getCourseNumber() { 121 return courseNumber; 122 } 123 124 public double[] getGradingWeights() { 125 return gradingWeights; 126 } 127 128 @Override 129 public int compareTo(Course o) { 130 Comparator<Object> compare = Collator.getInstance(Locale.CHINA); 131 return compare.compare(name, o.getName()); 132 } 133 } 134 135 class MyClass implements Comparable<MyClass> { 136 private final String classID; 137 ArrayList<Student> studentList = new ArrayList<>(); 138 139 public MyClass(String classID) { 140 this.classID = classID; 141 } 142 143 public void addStudent(Student student) { 144 studentList.add(student); 145 } 146 147 public String getClassID() { 148 return classID; 149 } 150 151 @Override 152 public int compareTo(MyClass other) { 153 return classID.compareTo(other.getClassID()); 154 } 155 } 156 class ParseInput{ 157 private final ArrayList<Course> courseList = new ArrayList<>(); 158 private final ArrayList<Student> studentList = new ArrayList<>(); 159 private final ArrayList<EnrollmentRecord> recordList = new ArrayList<>(); 160 private final ArrayList<MyClass> classList = new ArrayList<>(); 161 162 public void parseInput(String input) { 163 String[] inputArray = input.split(" "); 164 switch (InputMatching.matchingInput(input)) { 165 case 1: 166 inputCourse(inputArray); 167 break; 168 case 2: 169 inputScore(inputArray); 170 break; 171 default: 172 System.out.println("wrong format"); 173 break; 174 } 175 } 176 177 Course getCourse(String courseName){ 178 for (Course course : courseList) { 179 if (course.getName().equals(courseName)) 180 return course; 181 } 182 return null; 183 } 184 MyClass getClazz(String classId){ 185 for (MyClass MyClass : classList) { 186 if (MyClass.getClassID().equals(classId)) 187 return MyClass; 188 } 189 return null; 190 } 191 Student getStudent(String stuId){ 192 for (Student student : studentList) { 193 if (student.getStudentNumber().equals(stuId)) 194 return student; 195 } 196 return null; 197 } 198 199 private void inputScore(String[] a){ 200 MyClass myclass; 201 Student student; 202 myclass=getClazz(a[0].substring(0,6)); 203 if(myclass==null){ 204 myclass=new MyClass(a[0].substring(0,6)); 205 classList.add(myclass); 206 } 207 student=getStudent(a[0]); 208 if(student==null){ 209 student=new Student(a[0], a[1]); 210 studentList.add(student); 211 myclass.addStudent(student); 212 } 213 Course course=getCourse(a[2]); 214 if(course==null){ 215 System.out.println(a[2]+" does not exist"); 216 return; 217 } 218 if(!checkGrade(a,course)) 219 return; 220 Score score; 221 if(a.length==4){ 222 score=new KcScore(Integer.parseInt(a[3])); 223 } 224 else if(a.length==5) { 225 score=new KsScore(Integer.parseInt(a[3]),Integer.parseInt(a[4]),course.getGradingWeights()); 226 } 227 else { 228 int num = a.length-3; 229 int [] flag =new int[num]; 230 for (int i = 0; i < flag.length; i++) { 231 flag[i]=Integer.parseInt(a[i+3]); 232 } 233 score=new SyScore(flag,0,course.getGradingWeights()); 234 } 235 if(existChooseCourse(student,course)) return; 236 EnrollmentRecord chooseCourse = new EnrollmentRecord(course, student, score); 237 recordList.add(chooseCourse); 238 } 239 public void inputCourse(String[] a){ 240 Course course; 241 double [] weight; 242 if(a[2].equals("实验")&&a.length>7){ 243 weight = syweight(a); 244 course = new Course(a[0],a[1],a[2],Integer.parseInt(a[3]),weight); 245 } 246 else { 247 if (a[2].equals("考试")&&a.length==5) 248 { 249 weight = ksweight(a); 250 course = new Course(a[0], a[1], a[2], weight); 251 } 252 else 253 course = new Course(a[0],a[1],a[2]); 254 } 255 if(getCourse(a[0])!=null) return; 256 if(!checkCourse(a,course)) return; 257 if(getCourse(a[0])==null&&a[2].equals("考察")&&a.length==3){ 258 course=new Course(a[0], a[1], a[2]); 259 courseList.add(searchCourse(course)); 260 } 261 if(getCourse(a[0])==null&&a[2].equals("实验")&&a.length>=8){ 262 weight = syweight(a); 263 course=new Course(a[0], a[1], a[2],Integer.parseInt(a[3]),weight); 264 courseList.add(searchCourse(course)); 265 } 266 if(getCourse(a[0])==null&&a[2].equals("考试")&&a.length==5){ 267 weight = ksweight(a); 268 course=new Course(a[0], a[1], a[2],0,weight); 269 courseList.add(searchCourse(course)); 270 } 271 } 272 double[] ksweight(String[] b){ 273 double [] a = new double[2]; 274 for (int i = 0; i < a.length; i++) { 275 a[i]=Float.parseFloat(b[i+3]); 276 } 277 return a; 278 } 279 double [] syweight(String[] b){ 280 double [] a = new double[Integer.parseInt(b[3])]; 281 for (int i = 0; i < a.length; i++) { 282 a[i]= Float.parseFloat(b[i+4]); 283 } 284 return a; 285 } 286 boolean checkCourse(String[] items,Course course){ 287 if (items[2].equals("实验")&&items.length-4!=Integer.parseInt(items[3])){ 288 System.out.println(course.getName() + " : number of scores does not match"); 289 return false; 290 } 291 if (items[2].equals("实验")&&items.length-4==Integer.parseInt(items[3])){ 292 int num = Integer.parseInt(items[3]); 293 double sum=0; 294 int [] flag =new int[num]; 295 for (int i = 0; i < flag.length; i++) { 296 sum+=Double.parseDouble(items[i+4]); 297 } 298 if(sum>1.000001||sum<0.999999){ 299 System.out.println(course.getName() + " : weight value error"); 300 return false; 301 } 302 } 303 if (items[2].equals("考试")&&items.length==5){ 304 double sum= 0; 305 int [] flag =new int[2]; 306 for (int i = 0; i < flag.length; i++) { 307 sum+=Double.parseDouble(items[i+3]); 308 } 309 if(sum>1.000001||sum<0.999999){ 310 System.out.println(course.getName() + " : weight value error"); 311 return false; 312 } 313 } 314 if(course.getDescription().equals("必修")&&course.getExaminationType().equals("考试")) 315 return true; 316 if(course.getDescription().equals("选修")&&course.getExaminationType().equals("考试")) 317 return true; 318 if(course.getDescription().equals("选修")&&course.getExaminationType().equals("考察")) 319 return true; 320 if(course.getDescription().equals("实验")&&course.getExaminationType().equals("实验")) 321 return true; 322 System.out.println(course.getName()+" : course type & access mode mismatch"); 323 return false; 324 } 325 boolean existChooseCourse(Student stu,Course course){ 326 for (EnrollmentRecord choose : recordList) { 327 if (choose.getCourse().getName().equals(course.getName())) { 328 if (choose.getStudent().getStudentNumber().equals(stu.getStudentNumber())) 329 return true; 330 } 331 } 332 return false; 333 } 334 Course searchCourse(Course course){ 335 for (EnrollmentRecord choose : recordList) { 336 if (choose.getCourse().getName().equals(course.getName())) { 337 return null; 338 } 339 } 340 return course; 341 } 342 private boolean checkGrade(String[] items,Course course){ 343 String courseType=course.getExaminationType(); 344 if(courseType.equals("考试")&&items.length==5){ 345 return true; 346 } 347 if(courseType.equals("考察")&&items.length==4){ 348 return true; 349 } 350 if(courseType.equals("实验")&&items.length-3==course.getCourseNumber()){ 351 return true; 352 } 353 System.out.println(items[0]+" "+items[1]+" : access mode mismatch"); 354 return false; 355 } 356 public int getAvgTotalScore(ArrayList<EnrollmentRecord> listChooseCourse) 357 { 358 int sum =0; 359 for(EnrollmentRecord cs : listChooseCourse) 360 { 361 sum += cs.getScore().getTotalScore(); 362 } 363 return sum/listChooseCourse.size(); 364 } 365 public int getScore(ArrayList<EnrollmentRecord> courseSelects)//实验 366 { 367 float sum =0; 368 for(EnrollmentRecord cs : courseSelects) 369 { 370 sum += cs.getScore().getTotalScore(); 371 } 372 return (int)(sum/courseSelects.size()); 373 } 374 375 public ArrayList<EnrollmentRecord> getStudentSelects(String stNumber) { 376 ArrayList<EnrollmentRecord> stus = new ArrayList<>(); 377 for (EnrollmentRecord choose : recordList) { 378 if (choose.getStudent().getStudentNumber().equals(stNumber)) { 379 stus.add(choose); 380 } 381 } 382 if(stus.size()!=0) 383 return stus; 384 else return null; 385 } 386 387 public ArrayList<EnrollmentRecord> getCourseSelects(String courseName){ 388 ArrayList<EnrollmentRecord> courses = new ArrayList<>(); 389 for (EnrollmentRecord choose : recordList) { 390 if (choose.getCourse().getName().equals(courseName)) { 391 courses.add(choose); 392 } 393 } 394 if(courses.size()!=0) 395 return courses; 396 else return null; 397 } 398 399 public ArrayList<EnrollmentRecord> getClassSelects(String classID){ 400 ArrayList<EnrollmentRecord> classes = new ArrayList<>(); 401 for (EnrollmentRecord choose : recordList) { 402 if (choose.getStudent().getStudentNumber().substring(0, 6).equals(classID)) { 403 classes.add(choose); 404 } 405 } 406 if(classes.size()!=0) 407 return classes; 408 else return null; 409 } 410 public void showStudents() { 411 Collections.sort(studentList); 412 for (Student student : studentList) { 413 ArrayList<EnrollmentRecord> stuCourseSelects = getStudentSelects(student.getStudentNumber()); 414 //从总选课表Choose中获取该生的选课记录集合 415 if (stuCourseSelects != null) { 416 System.out.println(student.getStudentNumber() + " " + student.getStudentName() + " " + getAvgTotalScore(stuCourseSelects)); 417 } else { 418 System.out.println(student.getStudentNumber() + " " + student.getStudentName() + " " + "did not take any exams"); 419 } 420 } 421 } 422 423 public void showCourses() { 424 Collections.sort(courseList); 425 for (Course course : courseList) { 426 ArrayList<EnrollmentRecord> CourseSelects = getCourseSelects(course.getName()); 427 if (CourseSelects != null) { 428 if (course.getExaminationType().equals("考试")) 429 System.out.println(course.getName() + " " + getAvgTotalScore(CourseSelects)); 430 if (course.getExaminationType().equals("考察")) 431 System.out.println(course.getName() + " " + getAvgTotalScore(CourseSelects)); 432 if (course.getExaminationType().equals("实验")) 433 System.out.println(course.getName() + " " + getScore(CourseSelects)); 434 } else { 435 System.out.println(course.getName() + " has no grades yet"); 436 } 437 } 438 } 439 440 public void showClasses() { 441 Collections.sort(classList); 442 for (MyClass MyClass : classList) { 443 ArrayList<EnrollmentRecord> stuClassSelects = getClassSelects(MyClass.getClassID()); 444 if (stuClassSelects != null) { 445 System.out.println(MyClass.getClassID() + " " + getAvgTotalScore(stuClassSelects)); 446 } else { 447 System.out.println(MyClass.getClassID() + " " + "has no grades yet"); 448 } 449 } 450 } 451 } 452 class Student implements Comparable<Student>{ 453 private final String studentNumber; 454 private final String studentName; 455 456 public Student(String studentNumber, String studentName) { 457 this.studentName = studentName; 458 this.studentNumber = studentNumber; 459 } 460 461 public String getStudentNumber() { 462 return studentNumber; 463 } 464 465 public String getStudentName() { 466 return studentName; 467 } 468 469 @Override 470 public int compareTo(Student student) { 471 return getStudentNumber().compareTo(student.getStudentNumber()); 472 } 473 } 474 475 abstract class Score{ 476 public int finalScore; 477 public int totalScore; 478 479 public float getTotalScore() { 480 return totalScore; 481 } 482 483 Score(int finalScore){ 484 this.finalScore = finalScore; 485 } 486 } 487 488 class KsScore extends Score{//考试 489 490 KsScore(int usualScore, int finalScore, double[] weights){ 491 super(finalScore); 492 //平时 493 this.totalScore = (int)(usualScore * weights[0] + finalScore * weights[1]); 494 } 495 } 496 497 class KcScore extends Score{//考察 498 KcScore(int finalScore){ 499 super(finalScore); 500 this.totalScore = finalScore; 501 } 502 } 503 504 class SyScore extends Score{//实验 505 SyScore(int[] scores, int finalScore, double[] weights){ 506 super(finalScore); 507 double sum = 0; 508 for (int i = 0; i < scores.length; i++) { 509 sum += scores[i] * weights[i]; 510 } 511 this.totalScore = (int)(sum / scores.length); 512 } 513 }
这次也是在原有代码上做出一些改动就行。
以下是UML图:
正则表达式
正则表达式(Regular Expression)是由一些字符组成的模式,用来匹配和搜索字符串。在我的代码中,可以通过正则表达式提供的方法对输入的信息进行验证。下面举例说明:
-
验证输入是否是数字: 在代码中有一个自定义的方法
// 使用正则表达式判断字符串是否是数字 public static boolean isNumber(String str){ Pattern pattern = Pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); }isNumber
,用于判断输入的内容是否是数字。可以通过正则表达式实现同样的功能,代码如下:[0-9]*
表示匹配任意个数字,这里表示输入必须是由数字组成的字符串。 -
验证输入的菜品价格是否是正整数: 在输入菜品时,需要输入菜品的名称和价格。程序通过使用Scanner的
// 使用正则表达式判断字符串是否是正整数 public static boolean isPositiveInteger(String str){ Pattern pattern = Pattern.compile("^[1-9]\\d*$"); return pattern.matcher(str).matches(); }nextInt()
方法获取价格,但是如果输入的不是整数会导致程序崩溃。因此可以通过正则表达式验证输入的价格是否合法,代码如下:^
表示匹配行首,$
表示匹配行尾,[1-9]
表示第一位必须是1-9中的一个,\\d*
表示后面跟任意个数字。因此该表达式匹配任意个正整数。
通过在代码中使用正则表达式验证用户输入的字符串内容是否符合规范,可以保证程序的稳定性和安全性。
可见正则表达式可以简化代码,而且能够更加简单的应用,减少在写代码时,代码的逻辑问题,不过因为当时知识有限,还不知道正则表达式,更别说将其应用到点菜2中,对于正则表达式的学习,可以参考网站RegExr: Learn, Build, & Test RegEx。(注意使用时要导入java.util.regex.Pattern)
踩坑心得
本次题目踩坑的地方有:
- 成绩输入包含零分的情况,但是程序判断是否有成绩是通过初始值是否为零,故会有测试点过不去。
- 未能考虑判断的逻辑顺序,导致输入多组数据的时候不能给出有效输出。
主要困难及改进建议
1.代码的复杂度高,编程的质量不高,我认为要减少选择语句if else,改用switch或者数组,这样可以提高程序运行效率。
2.对于类的理解不够,一个类里面的属性与方法,应该有单一原则,单一职责原则核心思想是一个类,最好就做一件事。就如老师上课所说的类与类之间的关联性越小越好,而我所写的一些程序,互相关联的太多,导致不太好改。测试对于编码质量是非常重要的,虽然我们pta不对这个做要求,我们也应该对自己所编写的代码持有高度的严谨性,尽可能提高代码质量。
总结
这道题目涉及到了多个方面的内容,包括类的继承和组合关系、输入输出格式、数据约束、异常情况等。在解决这道题目的过程中,我学到了很多关于面向对象编程的知识,也更加熟悉了Java语言的使用。
在解决这道题目的过程中,我发现对于类的继承和组合关系,需要根据具体情况进行选择。继承关系可以使代码更加简洁,但是如果不当使用会导致代码的复杂性增加。而组合关系则可以更好地实现代码的复用,但是需要更多的代码量。因此,在实际编程中需要根据具体情况进行选择。
此外,在输入输出格式、数据约束、异常情况等方面,需要仔细考虑各种情况,并进行充分测试。在编写程序时,需要注意代码的可读性和可维护性,并尽可能地避免重复代码。
总之,在解决这道题目的过程中,我学到了很多关于面向对象编程和Java语言的知识,并且更加深入地理解了软件开发中的各个方面。
标签:return,String,int,Blog,course,student,public From: https://www.cnblogs.com/Zankjavablog/p/17510868.html