PTA第三阶段题目集总结以及对课程的建议

总结部分:

 

1.前言

  • 题目集7

         题目集4只有一题,整体难度中偏易

       题目7-1是对题目集4中的计价程序进行不同于题目集6的一种迭代,增加了口味度,并要求对每桌客人的口味度进行平均值计算。

  • 题目集8

         题目集8也只有一题,整体难度偏易

         题目7-1给出了参考类图,要求设计一个程序对学生的课程成绩进行统计。

  • 题目集9

       题目集9只有一题,题目量少但难度适中

       题目7-1要求编写程序统计一个输入的Java源码中关键字(区分大小写)出现的次数。(代码行数尽量少)

  • 题目集10 

       题目集10题量适中,整体难度适中

       题目7-1要求编写程序储存学生信息并使用HashMap根据学生的学号对学生进行检索

       题目7-2要求编写程序储存学生信息并使用HashMap根据学生的学号进行排序,相当于上一题的变种

         题目7-3课程成绩统计程序-2,对题目集8的课程成绩统计程序进行迭代,新增课程类型实验课,课程最终成绩为各次实验的平均分

         题目7-4动物发声模拟器,利用多态实现,题目较为简单

  • 题目集11

        题目7-1 容器-ArrayList-排序,利用容器ArrayList类对学生的成绩进行排序,较为简单

        题目7-2  课程成绩统计程序-3,再对题目集10中的课程成绩统计程序进行迭代,可以根据输入的课程分权重进行对学生成绩的计算

        题目7-3 Java-02基本语法-03-身份证排序,根据输入的身份证号提取出生日期并进行排序输出

        题目7-4 面向对象进阶-03-接口-自定义接口ArrayIntegerStack,自定义类模拟栈的实现

        题目7-5 Java-03面向对象基础-05-覆盖,定义PersonOverride类并覆盖其toStringequals方法。

2.设计与分析

  OOP训练集7

      7-1 菜单计价程序-5

      对Dish类进行修改,新增taste和tasteValue属性用于对顾客的口味值进行统计,再对Main类中的方法进行修改即可完成解答

      最终的类图如下:

       源码如下:

      

   1 import java.text.ParseException;
   2 import java.time.LocalDate;
   3 import java.time.LocalTime;
   4 import java.util.Scanner;
   5 
   6 @SuppressWarnings("unused")
   7 public class Main {
   8 
   9     @SuppressWarnings("resource")
  10     public static void main(String[] args) {
  11         // TODO Auto-generated method stub
  12         Scanner input = new Scanner(System.in);
  13         boolean islocked = false ;
  14         boolean isout = false ;
  15         
  16         String str;
  17         String[] s;
  18         Table table = new Table();
  19         Table[] tablelist = {table};
  20         Menu menu = Menu.getMenu();
  21         while(true) {
  22             str = input.nextLine();
  23             s = str.split(" ");
  24             
  25             //桌号
  26             if(s[0].matches("table")) {
  27                 
  28                 Order ordernew = new Order();
  29                 Table tablenew = new Table();
  30                 String[] arr_date = s[5].split("/");
  31                 s[6] = s[6].replaceAll("/", ":");
  32                 
  33                 if(!s[1].matches("\\d+")) {
  34                     System.out.println("wrong format");
  35                     islocked = true;
  36                     continue;
  37                 }
  38                 
  39                 LocalDate date = LocalDate.of(Integer.valueOf(arr_date[0]),Integer.valueOf(arr_date[1]) , Integer.valueOf(arr_date[2]));
  40                 LocalTime time = LocalTime.parse(s[6]);
  41                 tablenew = new Table(Integer.valueOf(s[1]),date,time,ordernew,s[3],s[4]);
  42                 
  43                 if(tablenew.isLegalOfTime() == 0) {
  44                     System.out.println("table " + tablenew.getTableNum() + " out of opening hours");
  45                     islocked = true;
  46                     continue;
  47                 }
  48                 
  49                 if(tablenew.isLegelOfTelephone() && tablenew.isLegelOfName()) {
  50                     System.out.println("wrong format");
  51                     islocked = true;
  52                     continue ;
  53                 }
  54                 
  55 //                System.out.println("table " + tablenew.getTableNum() + ": ");
  56                 tablelist = addtable(tablelist , tablenew);
  57                 isout = true;
  58             }
  59             
  60             //end退出循环
  61             else if(s[0].matches("end")) {
  62                 break;
  63             }
  64             
  65             //对订单的操作
  66             else if(s[0].matches("\\d+") && !islocked) {
  67                 
  68                 if(s[1].matches("delete")) {
  69                     if(!getlasttable(tablelist).getOrder().isExistOrderNum(Integer.valueOf(s[0]))) {
  70                         System.out.println("delete error");
  71                     }
  72                     else
  73                         getlasttable(tablelist).getOrder().delARecordByOrderNum(Integer.valueOf(s[0]));
  74                 }
  75                 
  76                 else if(s[1].matches("\\d")) {        //带点菜
  77                     
  78                 }
  79                 
  80                 else {
  81                     //菜品不存在
  82                     try {
  83                         if(menu.searthDish(s[1]).equals(null)) {  
  84                             System.out.println(s[1] + " does not exist");
  85                             continue;
  86                         }
  87                     }catch(Exception e) {
  88                         System.out.println("wrong format");
  89                         continue;
  90                     }
  91                     try {
  92                         if(s.length == 4) {   //非特色菜
  93                             getlasttable(tablelist).getOrder().addARecord(Integer.valueOf(s[0]), s[1], Integer.valueOf(s[2]), Integer.valueOf(s[3]));
  94 //                            System.out.println(Integer.valueOf(s[0]) + " " + s[1] + " " + menu.searthDish(s[1]).getPrice(Integer.valueOf(s[2]))*Integer.valueOf(s[3]));
  95                         }
  96                         if(s.length == 5) {   //特色菜
  97                             
  98                             getlasttable(tablelist).getOrder().addARecord(Integer.valueOf(s[0]), s[1], Integer.valueOf(s[3]), Integer.valueOf(s[4]) , Integer.valueOf(s[2]));
  99 //                            System.out.println(Integer.valueOf(s[0]) + " " + s[1] + " " + menu.searthDish(s[1]).getPrice(Integer.valueOf(s[3]))*Integer.valueOf(s[4]));
 100                             
 101                         
 102                         }
 103                     }catch(Exception e) {
 104                         System.out.println("wrong format");
 105                         continue;
 106                     }
 107                 }
 108             }
 109             
 110             //菜单加菜
 111             else {
 112                 if(!islocked) {
 113                     if(!isout) {
 114                         try {
 115                             if(menu.searthDish(s[0]) == null) {
 116                                 if(s.length == 2)
 117                                     menu.addDish(s[0], Integer.valueOf(s[1]));
 118                                 else
 119                                     menu.addDish(s[0], Integer.valueOf(s[2]),true,s[1]);
 120                             }
 121                             else {
 122                                 if(s.length == 2)
 123                                     menu.changeMenu(s[0], Integer.valueOf(s[1]));
 124                                 else
 125                                     menu.changeSpecialMenu(s[0], s[1], Integer.valueOf(s[2]));
 126                                     
 127                             }
 128                         }catch(Exception e) {
 129                             System.out.println("wrong format");
 130                             continue;
 131                         }
 132                     }
 133                     else
 134                         System.out.println("invalid dish");
 135                 }
 136             }
 137             
 138         }
 139         for(Table t : tablelist) {
 140             if(t != null ) {
 141                 try {
 142                     if( t.getOrder().getTotalPrice() > 0) {
 143                         System.out.println("table " + t.getTableNum() + ": ");
 144                         for(Record r : t.getOrder().getRecords()) {
 145                             if(!r.getD().isSpecial()) {
 146                                 System.out.println(r.getOrderNum() + " " + r.getD().getName() + " " +r.getPrice());
 147                             }
 148                             else {
 149                                 if(isLegalOfValue(r.getD().getTaste(),r.getTastevalue())) {
 150                                     System.out.println(r.getOrderNum() + " " + r.getD().getName() + " " +r.getPrice());
 151                                 }
 152                             }
 153                         }
 154                     }
 155                 }catch(Exception e) {
 156                     break;
 157                 }
 158             }
 159         }
 160         
 161         
 162         
 163         //循环结束输出各桌的总价以及折扣价
 164                 
 165                 for(Table t : tablelist) {
 166                     int pricefinal = 0;
 167                     int numofchuan = 0;  //川菜数
 168                     int spiciness = 0;     //辣度总和
 169                     int numofjin = 0;      //晋菜数
 170                     int acidity = 0;       //酸度总和
 171                     int numofzhe = 0;      //浙菜数
 172                     int sweetness =0;      //甜度总和
 173                     if(t != null && tablelist.length > 1) {
 174                         if(t.isLegalOfTime() == 1){
 175                             for(Record r : t.getOrder().getRecords()) {
 176                                 
 177                                 
 178                                 if(r.getD().isSpecial()) {
 179                                     
 180                                     if(!r.isLegaloftastevalue(r.getD().getTaste(), r.getTastevalue())) {
 181                                         r.setNum(0);
 182                                         continue;
 183                                     }
 184                                     if(r.getD().getTaste().matches("川菜")) {
 185                                         numofchuan += r.getNum();
 186                                         spiciness += r.getTastevalue()*r.getNum();
 187                                     }
 188                                     if(r.getD().getTaste().matches("晋菜")) {
 189                                         numofjin += r.getNum();
 190                                         acidity += r.getTastevalue()*r.getNum();
 191                                     }
 192                                     if(r.getD().getTaste().matches("浙菜")) {
 193                                         numofzhe += r.getNum();
 194                                         sweetness += r.getTastevalue()*r.getNum();
 195                                     }
 196                                 }
 197                                 if(r.getD().isSpecial())
 198                                     pricefinal += (int)(r.getPrice() * 0.7 + 0.6);
 199                                 else
 200                                     pricefinal += (int)(r.getPrice() * 0.6 + 0.6);
 201                             }
 202                             t.setRealprice(pricefinal);
 203                             if(pricefinal > 0) {
 204                                 System.out.print("table " + t.getTableNum() + ":" + " " + t.getOrder().getTotalPrice() + " " + pricefinal);
 205                             
 206                                 if(numofchuan > 0)
 207                                     System.out.print(" 川菜 " + numofchuan + " " + convertToAverageTasteValue("川菜",numofchuan,spiciness));
 208                                 if(numofjin > 0)
 209                                     System.out.print(" 晋菜 " + numofjin + " " + convertToAverageTasteValue("晋菜",numofjin,acidity));
 210                                 if(numofzhe > 0)
 211                                     System.out.print(" 浙菜 " + numofzhe + " " + convertToAverageTasteValue("浙菜",numofzhe,sweetness));
 212                                 System.out.println();
 213                             }
 214                         }
 215                     
 216                         else if(t.isLegalOfTime() == 2) {
 217                             for(Record r : t.getOrder().getRecords()) {
 218                                 if(r.getD().isSpecial()) {    
 219                                     if(!r.isLegaloftastevalue(r.getD().getTaste(), r.getTastevalue())) {
 220                                         r.setNum(0);
 221                                         continue;
 222                                     }
 223                                     if(r.getD().getTaste() != null) {
 224                                         if(r.getD().getTaste().matches("川菜")) {
 225                                             numofchuan += r.getNum();
 226                                             spiciness += r.getTastevalue()*r.getNum();
 227                                         }
 228                                         if(r.getD().getTaste().matches("晋菜")) {
 229                                             numofjin += r.getNum();
 230                                             acidity += r.getTastevalue()*r.getNum();
 231                                         }
 232                                         if(r.getD().getTaste().matches("浙菜")) {
 233                                             numofzhe += r.getNum();
 234                                             sweetness += r.getTastevalue()*r.getNum();
 235                                         }
 236                                     }
 237                                 }
 238                                 if(r.getD().isSpecial())
 239                                     pricefinal += (int)(r.getPrice() * 0.7 + 0.6);
 240                                 else
 241                                     pricefinal += (int)(r.getPrice() * 0.8 + 0.6);
 242                             }
 243                             t.setRealprice(pricefinal);
 244                             if(pricefinal >0) {
 245                                 System.out.print("table " + t.getTableNum() + ":" + " " + t.getOrder().getTotalPrice() + " " + pricefinal);
 246                             
 247                                 if(numofchuan > 0)
 248                                     System.out.print(" 川菜 " + numofchuan + " " + convertToAverageTasteValue("川菜",numofchuan,spiciness));
 249                                 if(numofjin > 0)
 250                                     System.out.print(" 晋菜 " + numofjin + " " + convertToAverageTasteValue("晋菜",numofjin,acidity));
 251                                 if(numofzhe > 0)
 252                                     System.out.print(" 浙菜 " + numofzhe + " " + convertToAverageTasteValue("浙菜",numofzhe,sweetness));
 253                                 System.out.println();
 254                             }
 255                         }
 256                         
 257                         else if(t.isLegalOfTime() == 3) {
 258                             
 259                             for(Record r : t.getOrder().getRecords()) {
 260                                 
 261                                 if(!r.getD().isSpecial())
 262                                     continue;
 263                                 if(!r.isLegaloftastevalue(r.getD().getTaste(), r.getTastevalue())) {
 264                                     r.setNum(0);
 265                                     continue;
 266                                 }
 267                                 if(r.getD().getTaste().matches("川菜")) {
 268                                     numofchuan += r.getNum();
 269                                     spiciness += r.getTastevalue()*r.getNum();
 270                                 }
 271                                 if(r.getD().getTaste().matches("晋菜")) {
 272                                     numofjin += r.getNum();
 273                                     acidity += r.getTastevalue()*r.getNum();
 274                                 }
 275                                 if(r.getD().getTaste().matches("浙菜")) {
 276                                     numofzhe += r.getNum();
 277                                     sweetness += r.getTastevalue()*r.getNum();
 278                                 }
 279                             }
 280                             pricefinal =t.getOrder().getTotalPrice();
 281                             t.setRealprice(pricefinal);
 282                             if(pricefinal > 0) {
 283                                 System.out.print("table " + t.getTableNum() + ":" + " " + t.getOrder().getTotalPrice() + " " + pricefinal);
 284                             
 285                                 if(numofchuan > 0)
 286                                     System.out.print(" 川菜 " + numofchuan + " " + convertToAverageTasteValue("川菜",numofchuan,spiciness));
 287                                 if(numofjin > 0)
 288                                     System.out.print(" 晋菜 " + numofjin + " " + convertToAverageTasteValue("晋菜",numofjin,acidity));
 289                                 if(numofzhe > 0)
 290                                     System.out.print(" 浙菜 " + numofzhe + " " + convertToAverageTasteValue("浙菜",numofzhe,sweetness));
 291                                 System.out.println();
 292                             }
 293                         }
 294                     }
 295                     
 296                 }
 297         
 298         //根据人名输出价格
 299         for(int i = 1 ; i < tablelist.length ; i++) {
 300             for(int j = i + 1 ; j < tablelist.length ; j++) {
 301                 if(tablelist[i].getName().compareToIgnoreCase(tablelist[j].getName()) > 0) {
 302                     Table temp = tablelist[i];
 303                     tablelist[i] = tablelist[j];
 304                     tablelist[j] = temp;
 305                 }
 306             }
 307         }
 308         int[] paylist = new int[tablelist.length];
 309         for(int i = 1 ; i < tablelist.length ; i++) {
 310             paylist[i] = tablelist[i].getRealprice();
 311         }
 312         for(int i = 1 ; i < tablelist.length ; i++) {
 313             int j;
 314             for(j = i + 1 ; j <tablelist.length ; j++) {
 315                 if(tablelist[i].getName().equals(tablelist[j].getName())) 
 316                     paylist[i] += paylist[j];  
 317                 else
 318                     break;
 319             }
 320             if(paylist[i] > 0)
 321                 System.out.println(tablelist[i].getName() + " " + tablelist[i].getTelephone() +" " + paylist[i]);
 322             i = j-1;
 323         }
 324 //        for(int i = 1 ; i < tablelist.length ; i++) {
 325 //            System.out.println(tablelist[i].getName());
 326 //        }
 327         
 328     }
 329     
 330     /**
 331      * 用于获取tablelist中的最后一个table
 332      * @param tablelist
 333      * @return
 334      */
 335     public static  Table getlasttable(Table[] tablelist) {
 336         Table table = new Table();
 337         table = tablelist[tablelist.length - 1];
 338         return table; 
 339     }
 340     
 341     /**
 342      * 用于判定是否菜品序号正确排序
 343      * @param table
 344      * @param x
 345      * @return
 346      */
 347     public static boolean issort(Table table , int x) {
 348         if(table.equals(null))
 349             return true;
 350         boolean flag = true;
 351         for(Record i : table.getOrder().getRecords()) {
 352             if(i.getOrderNum() >= x) {
 353                 flag = false;
 354                 break;
 355             }
 356         }
 357         return flag;
 358     }
 359     
 360     
 361     /**
 362      * 用于向tablelist数组中增加Table,实现数组的扩容
 363      * @param tablelist  需要增加table的数组
 364      * @param tablenew   所增加的table
 365      * @return           扩容后的新的数组
 366      */
 367     public static Table[] addtable(Table[] tablelist , Table tablenew) {
 368         
 369         if(tablelist.length == 1) {
 370             Table[] tablelistnew = new Table[2];
 371             tablelistnew[1] = tablenew;
 372             return tablelistnew;
 373         }
 374         else {
 375             Table[] tablelistnew = new Table[tablelist.length + 1];
 376             for(int i = 0 ; i < tablelist.length ; i++) {
 377                 tablelistnew[i] = tablelist[i];
 378             }
 379             tablelistnew[tablelist.length] = tablenew;
 380             return tablelistnew;
 381         }
 382         
 383     }
 384     /**
 385      * 根据菜系类型以及其他数据计算风味值
 386      * @param type       菜系类型
 387      * @param num        菜品数量
 388      * @param totalvalue 菜系风味值总和
 389      * @return
 390      */
 391     public static String convertToAverageTasteValue(String type, int num, int totalvalue) {
 392         int average = (int)((totalvalue*1.0/num*1.0)+0.6);
 393         if(type.matches("川菜")) {
 394             switch(average) {
 395             case 0:return "不辣";
 396             case 1:return "微辣";
 397             case 2:return "稍辣";
 398             case 3:return "辣";
 399             case 4:return "很辣";
 400             case 5:return "爆辣";
 401             }
 402         }
 403         if(type.matches("晋菜")) {
 404             switch(average) {
 405             case 0:return "不酸";
 406             case 1:return "微酸";
 407             case 2:return "稍酸";
 408             case 3:return "酸";
 409             case 4:return "很酸";
 410             }
 411         }
 412         if(type.matches("浙菜")) {
 413             switch(average) {
 414             case 0:return "不甜";
 415             case 1:return "微甜";
 416             case 2:return "稍甜";
 417             case 3:return "甜";
 418             }
 419         }
 420         return null;
 421     }
 422     /**
 423      * 用于判断是否风味值超范围
 424      * @param type 菜品类型
 425      * @param value 风味值
 426      * @return
 427      */
 428     public static boolean isLegalOfValue(String type, int value) {
 429         if(type.matches("川菜")) {
 430             if(value > -1 && value <6) 
 431                 return true;
 432             else {
 433                 System.out.println("spicy num out of range :" + value);
 434                 return false;
 435             }
 436         }
 437         if(type.matches("晋菜")) {
 438             if(value > -1 && value <5) 
 439                 return true;
 440             else {
 441                 System.out.println("acidity num out of range :" + value);
 442                 return false;
 443             }
 444         }
 445         if(type.matches("浙菜")) {
 446             if(value > -1 && value <4) 
 447                 return true;
 448             else {
 449                 System.out.println("sweetness num out of range :" + value);
 450                 return false;
 451             }
 452         }
 453         return false;
 454     }
 455 }
 456 
 457 
 458 
 459 
 460 class Dish{
 461     private String name;//菜品名称
 462     private int unit_price; //单价
 463     private boolean special = false;
 464     private String taste;
 465     private int tasteValue;
 466     
 467     public Dish() {
 468         super();
 469         // TODO Auto-generated constructor stub
 470     }
 471 
 472     
 473     
 474     public Dish(String name, int unit_price) {
 475         super();
 476         this.name = name;
 477         this.unit_price = unit_price;
 478     }
 479 
 480     
 481 
 482     public Dish(String name, int unit_price, int tasteValue) {
 483         super();
 484         this.name = name;
 485         this.unit_price = unit_price;
 486         this.tasteValue = tasteValue;
 487     }
 488 
 489 
 490 
 491     public Dish(String name, int unit_price, boolean special) {
 492         super();
 493         this.name = name;
 494         this.unit_price = unit_price;
 495         this.special = special;
 496     }
 497 
 498     public Dish(String name, int unit_price, boolean special, String taste) {
 499         super();
 500         this.name = name;
 501         this.unit_price = unit_price;
 502         this.special = special;
 503         this.taste = taste;
 504     }
 505 
 506 
 507 
 508     public Dish(String name, int unit_price, boolean special, String taste, int tasteValue) {
 509         super();
 510         this.name = name;
 511         this.unit_price = unit_price;
 512         this.special = special;
 513         this.taste = taste;
 514         this.tasteValue = tasteValue;
 515     }
 516 
 517     public String getName() {
 518         return name;
 519     }
 520 
 521     public void setName(String name) {
 522         this.name = name;
 523     }
 524 
 525     public int getUnit_price() {
 526         return unit_price;
 527     }
 528 
 529     public void setUnit_price(int unit_price) {
 530         this.unit_price = unit_price;
 531     }
 532 
 533     public String getTaste() {
 534         return taste;
 535     }
 536 
 537     public void setTaste(String taste) {
 538         this.taste = taste;
 539     }
 540 
 541     public int getTasteValue() {
 542         return tasteValue;
 543     }
 544 
 545     public void setTasteValue(int tasteValue) {
 546         this.tasteValue = tasteValue;
 547     }
 548     
 549     public boolean isSpecial() {
 550         return special;
 551     }
 552 
 553     public void setSpecial(boolean special) {
 554         this.special = special;
 555     }
 556 
 557     /**
 558      * 
 559      * @return 口味错误返回false
 560      */
 561     public boolean isLegalOfTaste() {
 562         if(this.taste.matches("川菜"))
 563             return true;
 564         if(this.taste.matches("晋菜"))
 565             return true;
 566         if(this.taste.matches("浙菜"))
 567             return true;
 568         return false;
 569     }
 570     
 571     /**
 572      * 
 573      * @return 口味度超过正常范围返回false
 574      */
 575     public boolean isLegalOfTasteValue() {
 576         if(this.taste.matches("川菜")) {
 577             if(this.tasteValue > 5 || this.tasteValue < 0)
 578                 return false;
 579         }
 580         if(this.taste.matches("晋菜")) {
 581             if(this.tasteValue > 4 || this.tasteValue < 0)
 582                 return false;
 583         }
 584         if(this.taste.matches("浙菜")) {
 585             if(this.tasteValue > 3 || this.tasteValue < 0)
 586                 return false;
 587         }
 588         return true;
 589     }
 590     
 591     /**
 592      * 计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份)
 593      * @param portion  菜品的份额
 594      * @return         菜品的价格 小份菜的价格=菜品的基础价格。中份菜的价格=菜品的基础价格1.5。小份菜的价格=菜品的基础价格2。
 595      */
 596     public int getPrice(int portion){
 597 
 598         switch(portion) {
 599         case 1: return (int)(this.unit_price+0.6); 
 600         case 2: return (int)((this.unit_price*1.5)+0.6);
 601         case 3: return (int)((this.unit_price*2.0)+0.6);
 602         }            
 603         return 0;
 604     }
 605 }
 606 class Menu {
 607     private static Menu menu = null;
 608     private Dish[] dishs = {};
 609     
 610     private Menu() {
 611         
 612     }
 613     
 614     public static Menu getMenu() {
 615         if(menu == null)
 616             menu = new Menu();
 617         return menu;
 618     }
 619 
 620     public Dish[] getDishs() {
 621         return dishs;
 622     }
 623 
 624     public void setDishs(Dish[] dishs) {
 625         this.dishs = dishs;
 626     }
 627     
 628     /**
 629      * 根据菜品名称搜寻菜品
 630      * @param dishName  菜品名称
 631      * @return          菜品
 632      */
 633     public Dish searthDish(String dishName) {
 634         for(Dish i: dishs) {
 635             if(i.getName().equals(dishName))
 636                 return i;
 637         }
 638         return null;
 639     }
 640     
 641     /**
 642      * 修改菜单信息
 643      * @param dishName
 644      * @param price
 645      * @param flag
 646      */
 647     public void changeSpecialMenu(String dishName , int price , boolean flag) {
 648         for(int i = 0 ; i < this.dishs.length ; i++) {
 649             if(dishName.equals(this.dishs[i].getName())) {
 650                 dishs[i] = new Dish( dishName, price, flag);
 651             }
 652         }
 653     }
 654     
 655     public void changeSpecialMenu(String dishName ,String type, int price ) {
 656         for(int i = 0 ; i < this.dishs.length ; i++) {
 657             if(dishName.equals(this.dishs[i].getName())) {
 658                 dishs[i] = new Dish( dishName, price, true, type);
 659             }
 660         }
 661     }
 662     
 663     /**
 664      * 修改菜单信息
 665      * @param dishName
 666      * @param price
 667      */
 668     public void changeMenu(String dishName , int price ) {
 669         for(int i = 0 ; i < this.dishs.length ; i++) {
 670             if(dishName.equals(this.dishs[i].getName())) {
 671                 dishs[i] = new Dish( dishName, price);
 672             }
 673         }
 674     }
 675     
 676     /**
 677      * 菜单加菜
 678      * @param dishName
 679      * @param unit_price
 680      * @return
 681      */
 682     public Dish addDish(String dishName,int unit_price) {
 683         Dish dish = new Dish(dishName , unit_price , false);
 684         Dish[] newdishs = new Dish[this.dishs.length+1];
 685         for(int i = 0 ; i < this.dishs.length ; i++) {
 686             newdishs[i] = this.dishs[i];
 687         }
 688         newdishs[this.dishs.length] = dish;
 689         this.dishs = newdishs ;
 690         return dish;
 691     }
 692     
 693     /**
 694      * 菜单加菜
 695      * @param dishName
 696      * @param unit_price
 697      * @param special
 698      * @return
 699      */
 700     public Dish addDish(String dishName,int unit_price,boolean special) {
 701         Dish dish = new Dish(dishName , unit_price , true);
 702         if(this.searthDish(dishName).getName().equals(dishName)) {
 703             for(int i = 0 ; i < this.dishs.length ; i++) {
 704                 if(this.dishs[i].getName().equals(dishName)) {
 705                     this.dishs[i].setUnit_price(unit_price);
 706                     this.dishs[i].setSpecial(special);
 707                 }
 708             }
 709         }
 710         else {
 711             Dish[] newdishs = new Dish[this.dishs.length+1];
 712             for(int i = 0 ; i < this.dishs.length ; i++) {
 713                 newdishs[i] = this.dishs[i];
 714             }
 715             newdishs[this.dishs.length] = dish;
 716             this.dishs = newdishs ;
 717         }
 718         
 719         return dish;
 720     }
 721     
 722     /**
 723      * 菜单增加特色菜
 724      * @param dishName        菜名
 725      * @param unit_price      价格
 726      * @param special         
 727      * @param taste           风味
 728      * @return
 729      */
 730     public Dish addDish(String dishName , int unit_price , boolean special , String taste ) {
 731         Dish dish = new Dish(dishName , unit_price , special , taste );
 732         Dish[] newdishs = new Dish[this.dishs.length+1];
 733         for(int i = 0 ; i < this.dishs.length ; i++) {
 734             newdishs[i] = this.dishs[i];
 735         }
 736         newdishs[this.dishs.length] = dish;
 737         this.dishs = newdishs ;
 738         return dish;
 739     }
 740 }
 741 
 742 class Order {
 743     Record[] records = {};//保存订单上每一道的记录
 744 
 745     public Order(Record[] records) {
 746         super();
 747         this.records = records;
 748     }
 749 
 750     public Order() {
 751         super();
 752         // TODO Auto-generated constructor stub
 753     }
 754 
 755     public Record[] getRecords() {
 756         return records;
 757     }
 758 
 759     public void setRecords(Record[] records) {
 760         this.records = records;
 761     }
 762     
 763     public int getTotalPrice(){//计算订单的总价
 764         int total = 0;
 765         for(Record i: records) {
 766             total += i.getPrice();
 767         }
 768         return total;
 769     }
 770     
 771     public Record addARecord(int orderNum,String dishName,int portion,int num) {
 772         Menu menu = Menu.getMenu();
 773         Record record = new Record(orderNum ,menu.searthDish(dishName),portion,num);
 774         Record[] newrecords = new Record[this.records.length+1];
 775         for(int i = 0 ; i < this.records.length ; i++) {
 776             newrecords[i] = records[i];
 777         }
 778         newrecords[this.records.length] = record;
 779         this.records = newrecords;
 780         return record;
 781     }
 782     
 783     public Record addARecord(int orderNum,String dishName,int portion,int num,int tastevalue) {
 784         Menu menu = Menu.getMenu();
 785         Record record = new Record(orderNum ,menu.searthDish(dishName),portion,num,tastevalue);
 786         Record[] newrecords = new Record[this.records.length+1];
 787         for(int i = 0 ; i < this.records.length ; i++) {
 788             newrecords[i] = records[i];
 789         }
 790         newrecords[this.records.length] = record;
 791         this.records = newrecords;
 792         return record;
 793     }
 794     
 795     public void delARecordByOrderNum(int orderNum){//根据序号删除一条记录
 796         boolean flag =false;
 797         for(Record i : this.records) {
 798             if(i.getOrderNum() == orderNum)
 799                 flag = true;
 800         }
 801         if(flag) {
 802             Record[] newrecords = new Record[this.records.length-1];
 803         for(int i = 0 ,k =0; i < this.records.length ; i++) {
 804             if(records[i].getOrderNum() != orderNum) {
 805                 newrecords[k] = this.records[i];
 806                 k++;
 807             }
 808         }
 809         this.records = newrecords;
 810         }
 811         else
 812             System.out.println("delete error");
 813     }
 814     
 815     public boolean isExistOrderNum(int orderNum) {
 816         boolean flag =false;
 817         for(Record i : this.records) {
 818             if(i.getOrderNum() == orderNum)
 819                 flag = true;
 820         }
 821         return flag;
 822     }
 823 }
 824 
 825  class Record {
 826     private int orderNum;//序号
 827 
 828     private Dish d;//菜品\\
 829 
 830     private int portion;//份额(1/2/3代表小/中/大份
 831     
 832     private int num;//份数
 833 
 834     private int tastevalue; //风味值
 835     
 836     public Record(int orderNum, Dish d, int portion,int num) {
 837         super();
 838         this.orderNum = orderNum;
 839         this.d = d;
 840         this.portion = portion;
 841         this.num = num;
 842     }
 843 
 844     public Record(int orderNum, Dish d, int portion, int num, int tastevalue) {
 845         super();
 846         this.orderNum = orderNum;
 847         this.d = d;
 848         this.portion = portion;
 849         this.num = num;
 850         this.tastevalue = tastevalue;
 851     }
 852 
 853     public Record() {
 854         super();
 855         // TODO Auto-generated constructor stub
 856     }
 857 
 858     public int getOrderNum() {
 859         return orderNum;
 860     }
 861 
 862     public void setOrderNum(int orderNum) {
 863         this.orderNum = orderNum;
 864     }
 865 
 866     public Dish getD() {
 867         return d;
 868     }
 869 
 870     public void setD(Dish d) {
 871         this.d = d;
 872     }
 873 
 874     public int getPortion() {
 875         return portion;
 876     }
 877 
 878     public void setPortion(int portion) {
 879         this.portion = portion;
 880     }
 881     
 882     public int getNum() {
 883         return num;
 884     }
 885 
 886     public void setNum(int num) {
 887         this.num = num;
 888     }
 889 
 890     public int getPrice() {
 891         
 892         return this.d.getPrice(this.portion)*num;
 893     }
 894 
 895     public int getTastevalue() {
 896         return tastevalue;
 897     }
 898 
 899     public void setTastevalue(int tastevalue) {
 900         this.tastevalue = tastevalue;
 901     }
 902     
 903     public boolean isLegaloftastevalue(String type, int value) {
 904         if(type.matches("川菜")) {
 905             if(value > -1 && value <6) 
 906                 return true;
 907             else {
 908                 
 909                 return false;
 910             }
 911         }
 912         if(type.matches("晋菜")) {
 913             if(value > -1 && value <5) 
 914                 return true;
 915             else {
 916                 
 917                 return false;
 918             }
 919         }
 920         if(type.matches("浙菜")) {
 921             if(value > -1 && value <4) 
 922                 return true;
 923             else {
 924                 return false;
 925             }
 926         }
 927         return false;
 928     }
 929     
 930 }
 931 
 932 
 933  class Table {
 934 private int tableNum;
 935     
 936     private LocalDate date;
 937     
 938     private LocalTime time;
 939 
 940     private Order order;
 941     
 942     private String name;
 943     private String telephone;
 944     private int realprice = 0;
 945     
 946     
 947     public Table(int tableNum, LocalDate date, LocalTime time, Order order, String name, String telephone) {
 948         super();
 949         this.tableNum = tableNum;
 950         this.date = date;
 951         this.time = time;
 952         this.order = order;
 953         this.name = name;
 954         this.telephone = telephone;
 955     }
 956 
 957     public Table(int tableNum, LocalDate date, LocalTime time, Order order) {
 958         super();
 959         this.tableNum = tableNum;
 960         this.date = date;
 961         this.time = time;
 962         this.order = order;
 963     }
 964 
 965     public Table() {
 966         super();
 967         // TODO Auto-generated constructor stub
 968     }
 969 
 970     public int getTableNum() {
 971         return tableNum;
 972     }
 973 
 974     public void setTableNum(int tableNum) {
 975         this.tableNum = tableNum;
 976     }
 977 
 978     public LocalDate getDate() {
 979         return date;
 980     }
 981 
 982     public void setDate(LocalDate date) {
 983         this.date = date;
 984     }
 985 
 986     public LocalTime getTime() {
 987         return time;
 988     }
 989 
 990     public void setTime(LocalTime time) {
 991         this.time = time;
 992     }
 993     
 994     public Order getOrder() {
 995         return order;
 996     }
 997 
 998     public void setOrder(Order order) {
 999         this.order = order;
1000     }
1001 
1002     public String getName() {
1003         return name;
1004     }
1005 
1006     public void setName(String name) {
1007         this.name = name;
1008     }
1009 
1010     public String getTelephone() {
1011         return telephone;
1012     }
1013 
1014     public void setTelephone(String telephone) {
1015         this.telephone = telephone;
1016     }
1017 
1018     public int getRealprice() {
1019         return realprice;
1020     }
1021 
1022     public void setRealprice(int realprice) {
1023         this.realprice = realprice;
1024     }
1025 
1026     /**
1027      * 判断名字长度是否大于10
1028      * @return
1029      */
1030     public boolean isLegelOfName(){
1031         if(this.name.length() > 10)
1032             return false;
1033         return true;
1034     }
1035     /**
1036      * 判断手机号格式
1037      * @return 正确返回true
1038      */
1039     public boolean isLegelOfTelephone() {
1040         String s = "^(18[019] | 13[356])[0-9]{8}$";
1041         if(this.telephone.matches(s) && this.telephone.length() == 11) {
1042             return true; 
1043         }
1044         return false;
1045     }
1046     public boolean isLegalOfTableNum() {
1047         if(this.tableNum >55 || this.tableNum <1)
1048             return false;
1049         else
1050             return true;
1051     }
1052     
1053     /**
1054      * 判断折扣
1055      * @return 返回0表示时间越界 ,1表示6折, 2表示8折 , 3表示不打折
1056      */
1057     public int isLegalOfTime() {
1058         LocalTime time1 = LocalTime.parse("09:29:59");
1059         LocalTime time2 = LocalTime.parse("21:30:01");
1060         LocalTime time3 = LocalTime.parse("10:29:59");
1061         LocalTime time4 = LocalTime.parse("14:30:01");
1062         LocalTime time5 = LocalTime.parse("16:59:59");
1063         LocalTime time6 = LocalTime.parse("20:30:01");
1064         if(this.date.getDayOfWeek().getValue() == 6 || this.date.getDayOfWeek().getValue() == 7) {
1065             if(this.time.isAfter(time1) && this.time.isBefore(time2))
1066                 return 3;
1067         }
1068         else {
1069             if((this.time.isAfter(time3) && this.time.isBefore(time4)))
1070                 return 1;
1071             if((this.time.isAfter(time5) && this.time.isBefore(time6)))
1072                 return 2;
1073         }
1074         return 0;
1075     }
1076     
1077     public boolean isValidDate() {
1078         LocalDate date1 = LocalDate.parse("2022-01-01");
1079         LocalDate date2 = LocalDate.parse("2023-12-31");
1080         if(this.date.isAfter(date1) && this.date.isBefore(date2))
1081             return true;
1082         else
1083             return false;
1084     }
1085     
1086 }

    OOP训练集8

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

      先根据类图写出了Student,Course,Class,Score四个类,然后写两个类ExamScores ,ExamineScores,并让其继承Score。

       接着在让各个类implements Comparable接口,用于排序。

      最后再完成主方法的接口即可,最终类图如下:

          源码如下:

      

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

public class Main {
    public static void main(String[] args){
        ArrayList<Course> courses = new ArrayList<>();
        ArrayList<CourseSelection> courseSelections = new ArrayList<>();
        ArrayList<Class> classes = new ArrayList<>();
        ArrayList<Student> students = new ArrayList<>();
        String str;
        Scanner input = new Scanner(System.in);
        boolean inputOver = false;
        while(!inputOver){
            str = input.nextLine();
            String[] strings = str.split(" ");
            if(strings.length == 3 && str.matches("^[\u4e00-\u9fa5A-Za-z]{1,10} (必修|选修) (考试|考察)$")){
                Course course = new Course(strings[0] , strings[1] , strings[2]);
                boolean repeat = false;
                if(!courses.isEmpty()){
                    for(Course c : courses ){
                        if(c.getName().equals(strings[0])){
                            repeat = true;
                            break;
                        }
                    }
                }
                if(repeat){
                    continue;
                }
                if(strings[1].equals("必修")){
                    if(strings[2].equals("考试"))
                        courses.add(course);
                    else
                        System.out.println(strings[0] + " : course type & access mode mismatch");
                }
                else
                    courses.add(course);
            }
            else if(strings.length == 1 && strings[0].equals("end")){
                inputOver = true;
            }

            //考核方式为考察
            else if (strings.length == 4 && str.matches("^\\d{8} [\u4e00-\u9fa5A-Za-z]{1,10} [\u4e00-\u9fa5A-Za-z]{1,10} (\\d|[1-9]\\d|100)$")) {
                if(isRepeatOfScore(courseSelections , strings[0] , strings[2])){
                    continue;
                }
                Score score = new ExamineScores(Integer.parseInt(strings[3]));

                Student student = new Student(strings[0] , strings[1]);
                if(students.isEmpty()){
                    students.add(student);
                }
                else{
                    boolean flag = false;
                    for (Student s : students){
                        if (s.getNumber().equals(student.getNumber())) {
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){
                        students.add(student);
                    }
                }


                //classes增加班级
                if(classes.isEmpty()){
                    classes.add(new Class(student.getNumber().substring(0,6)));
                    classes.get(0).addStudent(student);
                }
                else{
                    //
                    boolean flag = false;
                    for (Class c : classes){
                        if(c.getNum().equals(student.getNumber().substring(0,6))){
                            flag = true;
                            c.addStudent(student);
                        }
                    }
                    if(!flag){
                        classes.add(new Class(student.getNumber().substring(0,6)));
                        for(Class c : classes){
                            if(c.getNum().equals(student.getNumber().substring(0,6))) {
                                c.addStudent(student);
                            }
                        }

                    }

                }
                //courses加入课程
                Course course = null;
                for(Course c : courses){
                    if (c.getName().equals(strings[2])){
                        course = c;
                    }
                }
                if(course == null){
                    System.out.println(strings[2] + " does not exist");
                    continue;
                }

                if (course.getTestMode().equals("考试")) {
                    System.out.println(student.getNumber() + " " + student.getName() + " : access mode mismatch");
                    continue;
                }

                addStudentAndClassScore(courseSelections, classes, students, score, student, course);


            }

            //考核方式为考试
            else if(strings.length == 5 && str.matches("^\\d{8} [\u4e00-\u9fa5A-Za-z]{1,10} [\u4e00-\u9fa5A-Za-z]{1,10} (\\d|[1-9]\\d|100) (\\d|[1-9]\\d|100)$")){
                if(isRepeatOfScore(courseSelections , strings[0] , strings[2])){
                    continue;
                }
                Score score = new ExamScores(Integer.parseInt(strings[3]) , Integer.parseInt(strings[4]));

                //students加入学生
                Student student = new Student(strings[0] , strings[1]);
                if(students.isEmpty()){
                    students.add(student);
                }
                else{
                    boolean flag = false;
                    for (Student s : students){
                        if (s.getNumber().equals(student.getNumber())) {
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){
                        students.add(student);
                    }
                }

                //增加班级
                if(classes.isEmpty()){
                    classes.add(new Class(student.getNumber().substring(0,6)));
                    classes.get(0).addStudent(student);
                }
                else{
                    //
                    boolean flag = false;
                    for (Class c : classes){
                        if(c.getNum().equals(student.getNumber().substring(0,6))){
                            flag = true;
                            c.addStudent(student);
                        }
                    }
                    //如果没有找到与该学生相同的班级则新建一个
                    if(!flag){
                        classes.add(new Class(student.getNumber().substring(0,6)));
                        for(Class c : classes){
                            if(c.getNum().equals(student.getNumber().substring(0,6))) {
                                c.addStudent(student);
                            }
                        }

                    }

                }

                //courses加入课程
                Course course = null;
                for(Course c : courses){
                    if (c.getName().equals(strings[2])){
                        course = c;
                    }
                }
                if(course == null){
                    System.out.println(strings[2] + " does not exist");
                    continue;
                }

                if (course.getTestMode().equals("考察")) {
                    System.out.println(student.getNumber() + " " + student.getName() + " : access mode mismatch");
                    continue;
                }

                addStudentAndClassScore(courseSelections, classes, students, score, student, course);


            }
            else
                System.out.println("wrong format");
        }
        //输出学生的平均分
        students.sort(Comparator.naturalOrder());
        for(Student s : students){
            try{
                System.out.println(s.getNumber() + " "
                        + s.getName() + " "
                        + s.getAverageScore());
            }catch (Exception e){
                System.out.println(s.getNumber() + " " + s.getName() +" did not take any exams");
            }

        }


        //输出课程平均分
        for(CourseSelection selection : courseSelections ){
            for(Course course : courses){
                if(selection.getCourse().getName().equals(course.getName())){
                    if(selection.getScore() instanceof ExamScores){
                        course.addExamScore((ExamScores) (selection.getScore()));
                    }
                    else{
                        course.addExamineScore((ExamineScores) (selection.getScore()));
                    }
                }
            }
        }
        boolean legal = true;
        try {
            courses.sort(Comparator.naturalOrder());
        }catch (Exception e){
            for(Course course: courses){
                System.out.println(course.getName() +" has no grades yet");
                legal = false;
            }
        }
        if(legal){
            for (Course course : courses){
                try{
                    if(course.getAverageUsualScore() == 0){
                        System.out.println(course.getName() + " "
                                + course.getAverageFinalScore() + " "
                                + course.getAverageScore());
                    }
                    else {
                        System.out.println(course.getName() + " "
                                + course.getAverageUsualScore() + " "
                                + course.getAverageFinalScore() + " "
                                + course.getAverageScore());
                    }
                }catch (Exception e){
                    System.out.println(course.getName() +" has no grades yet");
                }

            }
        }



        //输出班级平均分
        classes.sort(Comparator.naturalOrder());
        for (Class c : classes){
            if(c.getClassAverageScore() != 0)
                System.out.println(c.getNum() + " " + c.getClassAverageScore());
            else
                System.out.println(c.getNum() + " has no grades yet");
        }
    }

    private static void addStudentAndClassScore(ArrayList<CourseSelection> courseSelections, ArrayList<Class> classes, ArrayList<Student> students, Score score, Student student, Course course) {
        for(Student s : students){
            if(s.getNumber().equals(student.getNumber())){
                s.addACourseOfScore(score.getScore());
            }
        }
        for (Class c : classes){
            if(c.getNum().equals(student.getNumber().substring(0,6))){
                c.addTotalScore(score.getScore());
            }
        }
        CourseSelection courseSelection = new CourseSelection(course , student , score);
        courseSelections.add(courseSelection);
    }

    public static boolean isRepeatOfScore(ArrayList<CourseSelection> courseSelections , String studentNum ,String courseName){
        boolean repeat = false;
        if(!courseSelections.isEmpty()){
            for (CourseSelection c : courseSelections){
                if(c.getStudent().getNumber().equals(studentNum) && c.getCourse().getName().equals(courseName)){
                    repeat = true;
                    break;
                }
            }
        }
        return repeat;
    }
}

 class Class implements Comparable<Class>{
    private String num;
    private ArrayList<Student> students = new ArrayList<>();
    private int totalScore = 0;

    public Class(String num) {
        this.num = num;
    }


    public String getNum() {
        return num;
    }


    public void addStudent(Student student){
        students.add(student);
    }

    public void addTotalScore(int studentScore){
        this.totalScore += studentScore;
    }

    public int getClassAverageScore(){
        return (int)(this.totalScore/students.size());
    }

    @Override
    public int compareTo(Class o) {
        if (Integer.parseInt(this.getNum()) > Integer.parseInt(o.getNum())) {
            return 1;
        }
        else if(Integer.parseInt(this.getNum()) < Integer.parseInt(o.getNum())) {
            return -1;
        }
        return 0;
    }
}
class CourseSelection implements Comparable<CourseSelection>{
    private Course course;
    private Student student;
    private Score score;


    public CourseSelection(Course course, Student student, Score score) {
        this.course = course;
        this.student = student;
        this.score = score;
    }

    public Course getCourse() {
        return course;
    }


    public Student getStudent() {
        return student;
    }



    public Score getScore() {
        return score;
    }


    @Override
    public int compareTo(CourseSelection o) {
        if(Integer.parseInt(this.student.getNumber()) > Integer.parseInt(o.getStudent().getNumber()))
            return 1;
        else if(Integer.parseInt(this.student.getNumber()) < Integer.parseInt(o.getStudent().getNumber()))
            return -1;
        return this.score.compareTo(o.score);
    }
}
 class Course implements Comparable<Course>{
    //课程名字
    private String name;
    //是否必修
    private String compulsory;
    //考核方式
    private String testMode;

    private int scoreTotal = 0;

    private int usualScoreTotal = 0;

    private int finalScoreTotal = 0;
    //选课人数
    private int num = 0;


    public Course(String name, String compulsory, String testMode) {
        this.name = name;
        this.compulsory = compulsory;
        this.testMode = testMode;
    }

    public String getName() {
        return name;
    }


    public String getTestMode() {
        return testMode;
    }


    public void addExamScore(ExamScores score){
        this.finalScoreTotal += score.getFinalScore();
        this.usualScoreTotal += score.getUsualScore();
        this.scoreTotal += score.getScore();
        this.num += 1;
    }

    public void  addExamineScore(ExamineScores score){
        this.finalScoreTotal += score.getScore();
        this.scoreTotal += score.getScore();
        this.num += 1;
    }

    public int getAverageScore(){
        return (int)(this.scoreTotal/num);
    }

    public int getAverageUsualScore(){
        return (int)(this.usualScoreTotal/num);
    }

    public int getAverageFinalScore(){
        return (int)(this.finalScoreTotal/num);
    }

    @Override
    public int compareTo(Course o) {
        Collator instance = Collator.getInstance(Locale.CHINA);

        return instance.compare(this.name,o.getName());
    }
}
 class ExamineScores extends Score{//考察成绩
    private int finalScore;

    public  ExamineScores(int finalScore){
        this.finalScore = finalScore;
    }


    @Override
    public int getScore() {
        return this.finalScore;
    }

    @Override
    public int compareTo(Score o) {
        if(this.getScore() > o.getScore())
            return -1;
        else if(this.getScore() < o.getScore())
            return 1;
        return 0;
    }
}
class ExamScores extends Score{//考试成绩
    private int usualScore;
    private int finalScore;

    public ExamScores(int usualScore, int finalScore) {
        this.usualScore = usualScore;
        this.finalScore = finalScore;
    }


    public int getUsualScore() {
        return usualScore;
    }


    public int getFinalScore() {
        return finalScore;
    }


    @Override
    public int getScore() {
        return (int)(usualScore * 0.3 + finalScore * 0.7);
    }

    @Override
    public int compareTo(Score o) {
        if(this.getScore() > o.getScore())
            return -1;
        else if(this.getScore() < o.getScore())
            return 1;
        return 0;
    }
}
 abstract class Score implements Comparable<Score>{
    private int score;

    public Score() {
    }
    public abstract int getScore();
}
class Student implements Comparable<Student>{
    private String number;
    private String name;
    private int courseNum = 0;
    private int totalScore = 0;

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

    public String getNumber() {
        return number;
    }


    public String getName() {
        return name;
    }


    public void addACourseOfScore(int score){
        this.courseNum += 1;
        this.totalScore += score;
    }

    public int getAverageScore(){
        return (int)(this.totalScore/this.courseNum);
    }

    @Override
    public int compareTo(Student o) {
        if(Integer.parseInt(this.getNumber()) > Integer.parseInt(o.getNumber()))
            return 1;
        else if (Integer.parseInt(this.getNumber()) < Integer.parseInt(o.getNumber())) {
            return -1;
        }
        return 0;
    }
}

 

 

OOP训练集9

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

        只需理解集合框架中的Map的用法以及提高程序模块化设计便可用尽可能少的代码行数完成解题。

 

        最终源码如下:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        HashMap<String,Integer> map = new HashMap<>();
        TreeMap<String,Integer> res = new TreeMap<>();
        String[] str = {"abstract","assert","boolean","break","byte","case","catch","char","class","continue","default","do","double","else","enum","extends","final","finally","float","for","if","implements","import","int","interface","instanceof","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while","goto","const","true","false","null"};
        for(int i=0; i<53; i++) map.put( str[i], 0);
        boolean flag = true;
        while(sc.hasNext()) {
            String s1 = sc.nextLine();
            StringBuilder s = new StringBuilder();
            if(s1.equals("exit")) break;
            flag = false;
            s.append(s1.replaceAll("\".*\"","").replaceAll("//.*","")); //运用正则表达式去除//注释的和双引号里的内容
            if(s.indexOf("/*")!=-1) { //删除/* */ 注释的
                if(s.indexOf("*/")!=-1) s.delete( s.indexOf("/*"), s.indexOf("*/")+2); // /* */注释没有跨行,删除/* */之间的内容
                else { // /* */跨行
                    s.delete( s.indexOf("/*"), s.length());
                    while(sc.hasNext()) { //一直输入直到出现 */
                        String sr = sc.nextLine();
                        if(sr.contains("*/")) {
                            s.append( sr.substring(sr.indexOf("*/")+2));
                            break;
                        }
                    }
                }
            }
            String sr = s.toString();
            sr = sr.replace("=", "a");
            int l = sr.length();
            for(int i=0; i<l; i++) {
                while(i<l && !check(sr.charAt(i))) {
                    i++;
                }
                int j = i;
                while(j<l && check(sr.charAt(j))){
                    j++;
                }
                if(i < l) {
                    String r = sr.substring( i, j); //把扫描出来的单词提前出来
                    if(map.containsKey(r)) { //判断是否是关键词
                        if(!res.containsKey(r)) res.put( r, 1);
                        else res.replace( r, (res.get(r)+1));
                    }
                }
                i = j;
            }
        }
        if( flag ) System.out.println("Wrong Format");
        else if(res.size()!=0){
            for(String i: res.keySet())
                System.out.println(res.get(i) + "\t" + i);
        }
    }
    public static boolean check( char x) {
        return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');
    }
}

OOP训练集10

      7-1 容器-HashMap-检索

        

      输入多个学生的成绩信息,包括:学号、姓名、成绩。

      学号是每个学生的唯一识别号,互不相同。

      姓名可能会存在重复。

      使用HashMap存储学生信息,并实现根据学号的检索功能

      输入格式:

      输入多个学生的成绩信息,每个学生的成绩信息格式:学号+英文空格+姓名+英文空格+成绩

      以“end”为输入结束标志

      end之后输入某个学号,执行程序输出该生的详细信息

      输出格式:  

      输出查询到的学生信息格式:学号+英文空格+姓名+英文空格+成绩

      如果没有查询到,则输出:"The student "+查询的学号+" does not exist"

 

       题目较为简单,根据要求完成解题即可,源码如下:

    

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

public class Main {
    public static void main(String[] args){
        HashMap<String, Student> studentHashMap= new HashMap<>();
        boolean inputOver = false;
        String str;
        Scanner input = new Scanner(System.in);
        while(!inputOver){
            str = input.nextLine();
            String[] strings = str.split(" ");
            if(strings.length == 3 && str.matches("^\\d{8} \\S{1,10} (\\d|[1-9]\\d|100)$")){
                Student student = new Student(strings[0],strings[1],strings[2]);
                studentHashMap.put(strings[0],student);
            }

            else if(strings.length == 1 && strings[0].equals("end")){
                inputOver = true;
            }

        }
        str = input.nextLine();
        if(studentHashMap.containsKey(str)) {
            System.out.println(studentHashMap.get(str).getNum() + " " + studentHashMap.get(str).getName() + " " + studentHashMap.get(str).getScore());
        }
        else {
            System.out.println("The student " + str + " does not exist");
        }


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


    public Student() {
    }

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

    public String getNum() {
        return num;
    }

    public String getName() {
        return name;
    }

    public String getScore() {
        return score;
    }
}

      7-2 容器-HashMap-排序

      重写比较器,根据比较器进行排序即可,源码如下:

import java.util.*;


public class Main {
    public static void main(String[] args){
        HashMap<String, Student> studentHashMap= new HashMap<>();
        Comparator comparatorInteger = new ComparatorInteger();
        boolean inputOver = false;
        String str;
        Scanner input = new Scanner(System.in);
        while(!inputOver){
            str = input.nextLine();
            String[] strings = str.split(" ");
            if(strings.length == 3 && str.matches("^\\d{8} \\S{1,10} (\\d|[1-9]\\d|100)$")){
                Student student = new Student(strings[0],strings[1],strings[2]);
                studentHashMap.put(strings[0],student);
            }

            else if(strings.length == 1 && strings[0].equals("end")){
                inputOver = true;
            }

        }
        Set set = studentHashMap.keySet();
        Object[] arr = set.toArray();
        Arrays.sort(arr,comparatorInteger);
        for(Object key : arr){
            System.out.println(studentHashMap.get(key).getNum() + " " + studentHashMap.get(key).getName() + " " + studentHashMap.get(key).getScore());
        }


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


    public Student() {
    }

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

    public String getNum() {
        return num;
    }

    public String getName() {
        return name;
    }

    public String getScore() {
        return score;
    }

}

class ComparatorInteger implements Comparator<String> {
    @Override   //使得逆序      o1比o2小,返回正数——需要调换位置
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }
}

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

      对先前的程序进行迭代,新增Experiment类继承Score类用于记录实验课程成绩,再对Main类进行相应修改即可,最终类图如下:

 

         源码如下:
      
import java.text.Collator;
import java.util.Locale;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        ArrayList<Course> courses = new ArrayList<>();
        ArrayList<CourseSelection> courseSelections = new ArrayList<>();
        ArrayList<Class> classes = new ArrayList<>();
        ArrayList<Student> students = new ArrayList<>();
        String str;
        Scanner input = new Scanner(System.in);
        boolean inputOver = false;
        while(!inputOver){
            str = input.nextLine();
            String[] strings = str.split(" ");
            if(strings.length == 3 && str.matches("^\\S{1,10} (必修|选修|实验) (考试|考察|实验)$")){
                Course course = new Course(strings[0] , strings[2]);
                boolean repeat = false;
                if(!courses.isEmpty()){
                    for(Course c : courses ){
                        if(c.getName().equals(strings[0])){
                            repeat = true;
                            break;
                        }
                    }
                }
                if(repeat){
                    continue;
                }
                if(strings[1].equals("必修")){
                    if(strings[2].equals("考试"))
                        courses.add(course);
                    else
                        System.out.println(strings[0] + " : course type & access mode mismatch");
                }
                else if(strings[1].equals("实验")){
                    if(strings[2].equals("实验"))
                        courses.add(course);
                    else
                        System.out.println(strings[0] + " : course type & access mode mismatch");
                }
                else
                    courses.add(course);
            }
            else if(strings.length == 1 && strings[0].equals("end")){
                inputOver = true;
            }

            //考核方式为考察
            else if (strings.length == 4 && str.matches("^\\d{8} \\S{1,10} \\S{1,10} (\\d|[1-9]\\d|100)$")) {
                if(isRepeatOfScore(courseSelections , strings[0] , strings[2])){
                    continue;
                }
                Score score = new ExamineScores(Integer.parseInt(strings[3]));

                //students加入学生
                Student student = new Student(strings[0] , strings[1]);
                if(students.isEmpty()){
                    students.add(student);
                }
                else{
                    boolean flag = false;
                    for (Student s : students){
                        if (s.getNumber().equals(student.getNumber())) {
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){
                        students.add(student);
                    }
                }


                //classes增加班级
                if(classes.isEmpty()){
                    classes.add(new Class(student.getNumber().substring(0,6)));
                    classes.get(0).addStudent(student);
                }
                else{
                    //
                    boolean flag = false;
                    for (Class c : classes){
                        if(c.getNum().equals(student.getNumber().substring(0,6))){
                            flag = true;
                            c.addStudent(student);
                        }
                    }

                    //如果没有找到与该学生相同的班级则新建一个
                    if(!flag){
                        classes.add(new Class(student.getNumber().substring(0,6)));
                        for(Class c : classes){
                            if(c.getNum().equals(student.getNumber().substring(0,6))) {
                                c.addStudent(student);
                            }
                        }

                    }

                }
                //courses加入课程
                Course course = null;
                for(Course c : courses){
                    if (c.getName().equals(strings[2])){
                        course = c;
                    }
                }
                if(course == null){
                    System.out.println(strings[2] + " does not exist");
                    continue;
                }

                if (!course.getTestMode().equals("考察")) {
                    System.out.println(student.getNumber() + " " + student.getName() + " : access mode mismatch");
                    continue;
                }

                addStudentAndClassScore(courseSelections, classes, students, score, student, course);


            }

            //考核方式为考试
            else if(strings.length == 5 && str.matches("^\\d{8} \\S{1,10} \\S{1,10} (\\d|[1-9]\\d|100) (\\d|[1-9]\\d|100)$")){
                if(isRepeatOfScore(courseSelections , strings[0] , strings[2])){
                    continue;
                }
                Score score = new ExamScores(Integer.parseInt(strings[3]) , Integer.parseInt(strings[4]));

                //students加入学生
                Student student = new Student(strings[0] , strings[1]);
                if(students.isEmpty()){
                    students.add(student);
                }
                else{
                    boolean flag = false;
                    for (Student s : students){
                        if (s.getNumber().equals(student.getNumber())) {
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){
                        students.add(student);
                    }
                }

                //增加班级
                if(classes.isEmpty()){
                    classes.add(new Class(student.getNumber().substring(0,6)));
                    classes.get(0).addStudent(student);
                }
                else{
                    //
                    boolean flag = false;
                    for (Class c : classes){
                        if(c.getNum().equals(student.getNumber().substring(0,6))){
                            flag = true;
                            c.addStudent(student);
                        }
                    }
                    //如果没有找到与该学生相同的班级则新建一个
                    if(!flag){
                        classes.add(new Class(student.getNumber().substring(0,6)));
                        for(Class c : classes){
                            if(c.getNum().equals(student.getNumber().substring(0,6))) {
                                c.addStudent(student);
                            }
                        }

                    }

                }

                //courses加入课程
                Course course = null;
                for(Course c : courses){
                    if (c.getName().equals(strings[2])){
                        course = c;
                    }
                }
                if(course == null){
                    System.out.println(strings[2] + " does not exist");
                    continue;
                }

                if (!course.getTestMode().equals("考试")) {
                    System.out.println(student.getNumber() + " " + student.getName() + " : access mode mismatch");
                    continue;
                }

                addStudentAndClassScore(courseSelections, classes, students, score, student, course);


            }
            else if (str.matches("^\\d{8} \\S{1,10} \\S{1,10} [4-9] ((\\d|[1-9]\\d|100) )*(\\d|[1-9]\\d|100)$")) {
                if(isRepeatOfScore(courseSelections , strings[0] , strings[2])){
                    continue;
                }
                boolean isOk = true;
                for (int i = 4 ; i < strings.length ;i++){
                    if(!strings[i].matches("(\\d|[1-9]\\d|100)")){
                        isOk = false;
                        break;
                    }
                }
                if(!isOk)
                    continue;
                Experiment score = new Experiment();
                for(int i = 4 ; i < strings.length ; i++){
                    score.addAExperimentScore(Integer.parseInt(strings[i]));
                }

                //students加入学生
                Student student = new Student(strings[0] , strings[1]);
                if(students.isEmpty()){
                    students.add(student);
                }
                else{
                    boolean flag = false;
                    for (Student s : students){
                        if (s.getNumber().equals(student.getNumber())) {
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){
                        students.add(student);
                    }
                }

                //增加班级
                if(classes.isEmpty()){
                    classes.add(new Class(student.getNumber().substring(0,6)));
                    classes.get(0).addStudent(student);
                }
                else{
                    //
                    boolean flag = false;
                    for (Class c : classes){
                        if(c.getNum().equals(student.getNumber().substring(0,6))){
                            flag = true;
                            c.addStudent(student);
                        }
                    }
                    //如果没有找到与该学生相同的班级则新建一个
                    if(!flag){
                        classes.add(new Class(student.getNumber().substring(0,6)));
                        for(Class c : classes){
                            if(c.getNum().equals(student.getNumber().substring(0,6))) {
                                c.addStudent(student);
                            }
                        }

                    }

                }

                //courses加入课程
                Course course = null;
                for(Course c : courses){
                    if (c.getName().equals(strings[2])){
                        course = c;
                    }
                }
                if(course == null){
                    System.out.println(strings[2] + " does not exist");
                    continue;
                }
                if (!course.getTestMode().equals("实验")||strings.length != Integer.parseInt(strings[3])+4) {
                    System.out.println(student.getNumber() + " " + student.getName() + " : access mode mismatch");
                    continue;
                }

                addStudentAndClassScore(courseSelections, classes, students, score, student, course);
            }
            else
                System.out.println("wrong format");
        }
        //输出学生的平均分
        students.sort(Comparator.naturalOrder());
        for(Student s : students){
            try{
                System.out.println(s.getNumber() + " "
                        + s.getName() + " "
                        + s.getAverageScore());
            }catch (Exception e){
                System.out.println(s.getNumber() + " " + s.getName() +" did not take any exams");
            }

        }


        //输出课程平均分
        for(CourseSelection selection : courseSelections ){
            for(Course course : courses){
                if(selection.getCourse().getName().equals(course.getName())){
                    if(selection.getScore() instanceof ExamScores){
                        course.addExamScore((ExamScores) (selection.getScore()));
                    }
                    else if(selection.getScore() instanceof ExamineScores){
                        course.addExamineScore((ExamineScores) (selection.getScore()));
                    }
                    else
                        course.addExperimentScore((Experiment) (selection.getScore()));
                }
            }
        }
        boolean legal = true;
        try {
            courses.sort(Comparator.naturalOrder());
        }catch (Exception e){
            for(Course course: courses){
                System.out.println(course.getName() +" has no grades yet");
                legal = false;
            }
        }
        if(legal){
            for (Course course : courses){
                try{
                    if(course.getTestMode().equals("考察")){
                        System.out.println(course.getName() + " "
                                + course.getAverageFinalScore() + " "
                                + course.getAverageScore());
                    }
                    else if(course.getTestMode().equals("实验")){
                        System.out.println(course.getName() + " "
                                + course.getAverageScore());
                    }
                    else {
                        System.out.println(course.getName() + " "
                                + course.getAverageUsualScore() + " "
                                + course.getAverageFinalScore() + " "
                                + course.getAverageScore());
                    }
                }catch (Exception e){
                    System.out.println(course.getName() +" has no grades yet");
                }

            }
        }



        //输出班级平均分
        classes.sort(Comparator.naturalOrder());
        for (Class c : classes){
            if(c.getClassAverageScore() != 0)
                System.out.println(c.getNum() + " " + c.getClassAverageScore());
            else
                System.out.println(c.getNum() + " has no grades yet");
        }
    }

    private static void addStudentAndClassScore(ArrayList<CourseSelection> courseSelections, ArrayList<Class> classes, ArrayList<Student> students, Score score, Student student, Course course) {
        for(Student s : students){
            if(s.getNumber().equals(student.getNumber())){
                s.addACourseOfScore(score.getScore());
            }
        }
        for (Class c : classes){
            if(c.getNum().equals(student.getNumber().substring(0,6))){
                c.addTotalScore(score.getScore());
            }
        }
        CourseSelection courseSelection = new CourseSelection(course , student , score);
        courseSelections.add(courseSelection);
    }

    public static boolean isRepeatOfScore(ArrayList<CourseSelection> courseSelections , String studentNum ,String courseName){
        boolean repeat = false;
        if(!courseSelections.isEmpty()){
            for (CourseSelection c : courseSelections){
                if(c.getStudent().getNumber().equals(studentNum) && c.getCourse().getName().equals(courseName)){
                    repeat = true;
                    break;
                }
            }
        }
        return repeat;
    }
}

class Class implements Comparable<Class>{
    private String num;
    private ArrayList<Student> students = new ArrayList<>();
    private int totalScore = 0;

    public Class(String num) {
        this.num = num;
    }


    public String getNum() {
        return num;
    }


    public void addStudent(Student student){
        students.add(student);
    }

    public void addTotalScore(int studentScore){
        this.totalScore += studentScore;
    }

    public int getClassAverageScore(){
        return this.totalScore/students.size();
    }

    @Override
    public int compareTo(Class o) {
        if (Integer.parseInt(this.getNum()) > Integer.parseInt(o.getNum())) {
            return 1;
        }
        else if(Integer.parseInt(this.getNum()) < Integer.parseInt(o.getNum())) {
            return -1;
        }
        return 0;
    }
}
class CourseSelection implements Comparable<CourseSelection>{
    private Course course;
    private Student student;
    private Score score;


    public CourseSelection(Course course, Student student, Score score) {
        this.course = course;
        this.student = student;
        this.score = score;
    }

    public Course getCourse() {
        return course;
    }


    public Student getStudent() {
        return student;
    }



    public Score getScore() {
        return score;
    }


    @Override
    public int compareTo(CourseSelection o) {
        if(Integer.parseInt(this.student.getNumber()) > Integer.parseInt(o.getStudent().getNumber()))
            return 1;
        else if(Integer.parseInt(this.student.getNumber()) < Integer.parseInt(o.getStudent().getNumber()))
            return -1;
        return this.score.compareTo(o.score);
    }
}
class Course implements Comparable<Course>{
    //课程名字
    private String name;
    //考核方式
    private String testMode;

    private int scoreTotal = 0;

    private int usualScoreTotal = 0;

    private int finalScoreTotal = 0;
    //选课人数
    private int num = 0;


    public Course(String name, String testMode) {
        this.name = name;
        //是否必修
        this.testMode = testMode;
    }

    public String getName() {
        return name;
    }


    public String getTestMode() {
        return testMode;
    }


    public void addExamScore(ExamScores score){
        this.finalScoreTotal += score.getFinalScore();
        this.usualScoreTotal += score.getUsualScore();
        this.scoreTotal += score.getScore();
        this.num += 1;
    }

    public void  addExamineScore(ExamineScores score){
        this.finalScoreTotal += score.getScore();
        this.scoreTotal += score.getScore();
        this.num += 1;
    }

    public void addExperimentScore(Experiment score){
        this.finalScoreTotal += score.getScore();
        this.scoreTotal += score.getScore();
        this.num += 1;
    }

    public int getAverageScore(){
        return this.scoreTotal/num;
    }

    public int getAverageUsualScore(){
        return this.usualScoreTotal/num;
    }

    public int getAverageFinalScore(){
        return this.finalScoreTotal/num;
    }

    @Override
    public int compareTo(Course o) {
        Collator instance = Collator.getInstance(Locale.CHINA);

        return instance.compare(this.name,o.getName());
    }
}
class ExamineScores extends Score{//考察成绩
    private int finalScore;

    public  ExamineScores(int finalScore){
        this.finalScore = finalScore;
    }


    @Override
    public int getScore() {
        return this.finalScore;
    }

    @Override
    public int compareTo(Score o) {
        if(this.getScore() > o.getScore())
            return -1;
        else if(this.getScore() < o.getScore())
            return 1;
        return 0;
    }
}
class ExamScores extends Score{//考试成绩
    private int usualScore;
    private int finalScore;

    public ExamScores(int usualScore, int finalScore) {
        this.usualScore = usualScore;
        this.finalScore = finalScore;
    }


    public int getUsualScore() {
        return usualScore;
    }


    public int getFinalScore() {
        return finalScore;
    }


    @Override
    public int getScore() {
        return (int)(usualScore * 0.3 + finalScore * 0.7);
    }

    @Override
    public int compareTo(Score o) {
        if(this.getScore() > o.getScore())
            return -1;
        else if(this.getScore() < o.getScore())
            return 1;
        return 0;
    }
}
abstract class Score implements Comparable<Score>{

    public Score() {
    }
    public abstract int getScore();
}
class Experiment extends Score{
    ArrayList<Integer> scores = new ArrayList<>();

    public Experiment() {
    }

    public void addAExperimentScore(int score){
        this.scores.add(score);
    }

    @Override
    public int getScore() {
        int totalScore = 0;
        for(Integer score : this.scores){
            totalScore += score;
        }

        return totalScore/this.scores.size();
    }

    @Override
    public int compareTo(Score o) {
        return Integer.compare(this.getScore(),o.getScore());
    }
}


class Student implements Comparable<Student>{
    private String number;
    private String name;
    private int courseNum = 0;
    private int totalScore = 0;

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

    public String getNumber() {
        return number;
    }


    public String getName() {
        return name;
    }


    public void addACourseOfScore(int score){
        this.courseNum += 1;
        this.totalScore += score;
    }

    public int getAverageScore(){
        return this.totalScore/this.courseNum;
    }

    @Override
    public int compareTo(Student o) {
        if(Integer.parseInt(this.getNumber()) > Integer.parseInt(o.getNumber()))
            return 1;
        else if (Integer.parseInt(this.getNumber()) < Integer.parseInt(o.getNumber())) {
            return -1;
        }
        return 0;
    }
}

       7-4 动物发声模拟器(多态)

       该题较为简单,利用多态即可轻松实现,源码如下:

//动物发生模拟器.  请在下面的【】处添加代码。
public class Main {
    public static void main(String[] args) {
        Cat cat = new Cat();
        Dog dog = new Dog();
        Goat goat = new Goat();
        speak(cat);
        speak(dog);
        speak(goat);
    }
    //定义静态方法speak()
    public static void speak(Animal animal){
        if(animal.getClass() == Dog.class){
            System.out.println("狗的叫声:" + animal.shout());
        }
        else if(animal.getClass() == Cat.class){
            System.out.println("猫的叫声:" + animal.shout());
        }
        else if(animal.getClass() == Goat.class){
            System.out.println("山羊的叫声:" + animal.shout());
        }
    }

}

//定义抽象类Animal
abstract class Animal{
    public abstract Class getAnimalClass();
    public abstract String shout();
}
//基于Animal类,定义猫类Cat,并重写两个抽象方法
class Cat extends Animal{

    @Override
    public Class getAnimalClass() {

        return this.getClass();
    }

    @Override
    public String shout() {
        return "喵喵";
    }
}
//基于Animal类,定义狗类Dog,并重写两个抽象方法
class Dog extends Animal {


    @Override
    public Class getAnimalClass() {
        return this.getClass();
    }

    @Override
    public String shout() {
        return "汪汪";
    }
}
//基于Animal类,定义山羊类Goat,并重写两个抽象方法
class Goat extends Animal{


    @Override
    public Class getAnimalClass() {
        return this.getClass();
    }

    @Override
    public String shout() {
        return "咩咩";
    }
}

OOP训练集11

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

    再对先前的代码进行迭代,根据输入课程信息时输入的权重比例计算考试与实验的分数

    修改ExamScore类中计算分数的方法和Experiment类中计算分数的代码,接着修改主方法中的部分代码即可

    最终类图如下:

       源码如下:

    

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

public class Main {
    public static void main(String[] args){
        ArrayList<Course> courses = new ArrayList<>();
        ArrayList<CourseSelection> courseSelections = new ArrayList<>();
        ArrayList<Class> classes = new ArrayList<>();
        ArrayList<Student> students = new ArrayList<>();
        String str;
        Scanner input = new Scanner(System.in);
        boolean inputOver = false;
        while(!inputOver) {
            str = input.nextLine();
            String[] strings = str.split(" ");
            if(strings.length == 3 && str.matches("^\\S{1,10} 选修 (考试|考察|实验)$")){
                Course course = new Course(strings[0] , strings[2]);
                if(isRepeatOfCourse(courses,strings[0])){
                    continue;
                }
                if(strings[2].equals("实验")){
                    System.out.println(strings[0] + " : course type & access mode mismatch");
                }
                else {
                    courses.add(course);
                }
            }
            else if(strings.length == 5 && str.matches("^\\S{1,10} 必修 (考试|考察|实验) (0\\.\\d+) (0\\.\\d+)$")){
                Course course = new Course(strings[0] , strings[2] , Double.parseDouble(strings[3]) , Double.parseDouble(strings[4]));
                if(isRepeatOfCourse(courses,strings[0])){
                    continue;
                }
                if(Double.parseDouble(strings[3]) + Double.parseDouble(strings[4]) != 1){
                    System.out.println(strings[0] + " : weight value error");
                    continue;
                }

                if(strings[2].equals("考试")){
                    courses.add(course);
                }
                else{
                    System.out.println(strings[0] + " : course type & access mode mismatch");
                }
            }
            else if(str.matches("^\\S{1,10} 实验 (考试|考察|实验) [4-9] ((0\\.\\d+) )*(0\\.\\d+)$")){
                ArrayList<Double> rateList = new ArrayList<>();
                for(int i = 4; i < strings.length ;i++){
                    double d = Double.parseDouble(strings[i]);
                    rateList.add(d);
                }
                Course course = new Course(strings[0] , strings[2] , rateList);
                if(isRepeatOfCourse(courses,strings[0])){
                    continue;
                }
                if(strings.length - 4 != Integer.parseInt(strings[3])){
                    System.out.println(strings[0] + " : number of scores does not match");
                    continue;
                }
                double totalRate = 0;
                for(Double d : rateList){
                    totalRate += d;
                }
                if(totalRate != 1){
                    System.out.println(strings[0] + " : weight value error");
                    continue;
                }

                if(strings[2].equals("实验")){
                    courses.add(course);
                }
                else{
                    System.out.println(strings[0] + " : course type & access mode mismatch");
                }
            }
            else if(strings.length == 1 && strings[0].equals("end")){
                inputOver = true;
            }
            //考察
            else if (strings.length == 4 && str.matches("^\\d{8} \\S{1,10} \\S{1,10} (\\d|[1-9]\\d|100)$")){
                if(isRepeatOfScore(courseSelections , strings[0] , strings[2])){
                    continue;
                }
                Score score = new ExamineScores(Integer.parseInt(strings[3]));

                //students加入学生
                Student student = new Student(strings[0] , strings[1]);
                if(students.isEmpty()){
                    students.add(student);
                }
                else{
                    boolean flag = false;
                    for (Student s : students){
                        if (s.getNumber().equals(student.getNumber())) {
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){
                        students.add(student);
                    }
                }

                //classes增加班级
                if(classes.isEmpty()){
                    classes.add(new Class(student.getNumber().substring(0,6)));
                    classes.get(0).addStudent(student);
                }
                else{
                    //
                    boolean flag = false;
                    for (Class c : classes){
                        if(c.getNum().equals(student.getNumber().substring(0,6))){
                            flag = true;
                            c.addStudent(student);
                        }
                    }

                    //如果没有找到与该学生相同的班级则新建一个
                    if(!flag){
                        classes.add(new Class(student.getNumber().substring(0,6)));
                        for(Class c : classes){
                            if(c.getNum().equals(student.getNumber().substring(0,6))) {
                                c.addStudent(student);
                            }
                        }

                    }

                }
                //courses加入课程
                Course course = null;
                for(Course c : courses){
                    if (c.getName().equals(strings[2])){
                        course = c;
                    }
                }
                if(course == null){
                    System.out.println(strings[2] + " does not exist");
                    continue;
                }

                if (!course.getTestMode().equals("考察")) {
                    System.out.println(student.getNumber() + " " + student.getName() + " : access mode mismatch");
                    continue;
                }

                addStudentAndClassScore(courseSelections, classes, students, score, student, course);




            }
            //考试
            else if(strings.length == 5 && str.matches("^\\d{8} \\S{1,10} \\S{1,10} (\\d|[1-9]\\d|100) (\\d|[1-9]\\d|100)$")){
                if(isRepeatOfScore(courseSelections , strings[0] , strings[2])){
                    continue;
                }
                ExamScores score = new ExamScores(Integer.parseInt(strings[3]) , Integer.parseInt(strings[4]));

                //students加入学生
                Student student = new Student(strings[0] , strings[1]);
                if(students.isEmpty()){
                    students.add(student);
                }
                else{
                    boolean flag = false;
                    for (Student s : students){
                        if (s.getNumber().equals(student.getNumber())) {
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){
                        students.add(student);
                    }
                }

                //增加班级
                if(classes.isEmpty()){
                    classes.add(new Class(student.getNumber().substring(0,6)));
                    classes.get(0).addStudent(student);
                }
                else{
                    //
                    boolean flag = false;
                    for (Class c : classes){
                        if(c.getNum().equals(student.getNumber().substring(0,6))){
                            flag = true;
                            c.addStudent(student);
                        }
                    }
                    //如果没有找到与该学生相同的班级则新建一个
                    if(!flag){
                        classes.add(new Class(student.getNumber().substring(0,6)));
                        for(Class c : classes){
                            if(c.getNum().equals(student.getNumber().substring(0,6))) {
                                c.addStudent(student);
                            }
                        }

                    }

                }

                //courses加入课程
                Course course = null;
                for(Course c : courses){
                    if (c.getName().equals(strings[2])){
                        course = c;
                    }
                }
                if(course == null){
                    System.out.println(strings[2] + " does not exist");
                    continue;
                }

                if (!course.getTestMode().equals("考试")) {
                    System.out.println(student.getNumber() + " " + student.getName() + " : access mode mismatch");
                    continue;
                }
                score.setFinalRate(course.getFinalRate());
                score.setUsualRate(course.getUsualRate());
                addStudentAndClassScore(courseSelections, classes, students, score, student, course);


            }
            //实验
            else if (str.matches("^\\d{8} \\S{1,10} \\S{1,10} ((\\d|[1-9]\\d|100) )*(\\d|[1-9]\\d|100)$")){
                if(isRepeatOfScore(courseSelections , strings[0] , strings[2])){
                    continue;
                }
                boolean isOk = true;
                for (int i = 3 ; i < strings.length ;i++){
                    if(!strings[i].matches("(\\d|[1-9]\\d|100)")){
                        isOk = false;
                        break;
                    }
                }
                if(!isOk)
                    continue;
                Experiment score = new Experiment();
                for(int i = 3 ; i < strings.length ; i++){
                    score.addAExperimentScore(Integer.parseInt(strings[i]));
                }

                //students加入学生
                Student student = new Student(strings[0] , strings[1]);
                if(students.isEmpty()){
                    students.add(student);
                }
                else{
                    boolean flag = false;
                    for (Student s : students){
                        if (s.getNumber().equals(student.getNumber())) {
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){
                        students.add(student);
                    }
                }

                //增加班级
                if(classes.isEmpty()){
                    classes.add(new Class(student.getNumber().substring(0,6)));
                    classes.get(0).addStudent(student);
                }
                else{
                    //
                    boolean flag = false;
                    for (Class c : classes){
                        if(c.getNum().equals(student.getNumber().substring(0,6))){
                            flag = true;
                            c.addStudent(student);
                        }
                    }
                    //如果没有找到与该学生相同的班级则新建一个
                    if(!flag){
                        classes.add(new Class(student.getNumber().substring(0,6)));
                        for(Class c : classes){
                            if(c.getNum().equals(student.getNumber().substring(0,6))) {
                                c.addStudent(student);
                            }
                        }

                    }

                }

                //courses加入课程
                Course course = null;
                for(Course c : courses){
                    if (c.getName().equals(strings[2])){
                        course = c;
                    }
                }
                if(course == null){
                    System.out.println(strings[2] + " does not exist");
                    continue;
                }
                if (!course.getTestMode().equals("实验")||strings.length != course.getRateList().size() + 3) {
                    System.out.println(student.getNumber() + " " + student.getName() + " : access mode mismatch");
                    continue;
                }

                score.setRateList(course.getRateList());
                addStudentAndClassScore(courseSelections, classes, students, score, student, course);
            }
            else
                System.out.println("wrong format");
        }
        //输出学生的平均分
        students.sort(Comparator.naturalOrder());
        for(Student s : students){
            try{
                System.out.println(s.getNumber() + " "
                        + s.getName() + " "
                        + s.getAverageScore());
            }catch (Exception e){
                System.out.println(s.getNumber() + " " + s.getName() +" did not take any exams");
            }

        }


        //输出课程平均分
        for(CourseSelection selection : courseSelections ){
            for(Course course : courses){
                if(selection.getCourse().getName().equals(course.getName())){
                    if(selection.getScore() instanceof ExamScores){
                        course.addExamScore((ExamScores) (selection.getScore()));
                    }
                    else if(selection.getScore() instanceof ExamineScores){
                        course.addExamineScore((ExamineScores) (selection.getScore()));
                    }
                    else
                        course.addExperimentScore((Experiment) (selection.getScore()));
                }
            }
        }
        boolean legal = true;
        try {
            courses.sort(Comparator.naturalOrder());
        }catch (Exception e){
            for(Course course: courses){
                System.out.println(course.getName() +" has no grades yet");
                legal = false;
            }
        }
        if(legal){
            for (Course course : courses){
                try{
                    if(course.getTestMode().equals("考察")){
                        System.out.println(course.getName() + " "
                                + course.getAverageFinalScore() + " "
                                + course.getAverageScore());
                    }
                    else if(course.getTestMode().equals("实验")){
                        System.out.println(course.getName() + " "
                                + course.getAverageScore());
                    }
                    else {
                        System.out.println(course.getName() + " "
                                + course.getAverageUsualScore() + " "
                                + course.getAverageFinalScore() + " "
                                + course.getAverageScore());
                    }
                }catch (Exception e){
                    System.out.println(course.getName() +" has no grades yet");
                }

            }
        }



        //输出班级平均分
        classes.sort(Comparator.naturalOrder());
        for (Class c : classes){
            if(c.getClassAverageScore() != 0)
                System.out.println(c.getNum() + " " + c.getClassAverageScore());
            else
                System.out.println(c.getNum() + " has no grades yet");
        }





    }
    public static boolean isRepeatOfCourse(ArrayList<Course> courses , String str){
        boolean repeat = false;
        if(!courses.isEmpty()){
            for(Course c : courses ){
                if(c.getName().equals(str)){
                    repeat = true;
                    break;
                }
            }
        }
        return repeat;
    }

    public static boolean isRepeatOfScore(ArrayList<CourseSelection> courseSelections , String studentNum ,String courseName){
        boolean repeat = false;
        if(!courseSelections.isEmpty()){
            for (CourseSelection c : courseSelections){
                if(c.getStudent().getNumber().equals(studentNum) && c.getCourse().getName().equals(courseName)){
                    repeat = true;
                    break;
                }
            }
        }
        return repeat;
    }

    private static void addStudentAndClassScore(ArrayList<CourseSelection> courseSelections, ArrayList<Class> classes, ArrayList<Student> students, Score score, Student student, Course course) {
        for(Student s : students){
            if(s.getNumber().equals(student.getNumber())){
                s.addACourseOfScore(score.getScore());
            }
        }
        for (Class c : classes){
            if(c.getNum().equals(student.getNumber().substring(0,6))){
                c.addTotalScore(score.getScore());
            }
        }
        CourseSelection courseSelection = new CourseSelection(course , student , score);
        courseSelections.add(courseSelection);
    }

}
class Class implements Comparable<Class>{
    private String num;
    private ArrayList<Student> students = new ArrayList<>();
    private int totalScore = 0;

    public Class(String num) {
        this.num = num;
    }


    public String getNum() {
        return num;
    }


    public void addStudent(Student student){
        students.add(student);
    }

    public void addTotalScore(int studentScore){
        this.totalScore += studentScore;
    }

    public int getClassAverageScore(){
        return this.totalScore/students.size();
    }

    @Override
    public int compareTo(Class o) {
        if (Integer.parseInt(this.getNum()) > Integer.parseInt(o.getNum())) {
            return 1;
        }
        else if(Integer.parseInt(this.getNum()) < Integer.parseInt(o.getNum())) {
            return -1;
        }
        return 0;
    }
}
//学生
class Student implements Comparable<Student>{
    private String number;
    private String name;
    private int courseNum = 0;
    private int totalScore = 0;

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

    public String getNumber() {
        return number;
    }


    public String getName() {
        return name;
    }


    public void addACourseOfScore(int score){
        this.courseNum += 1;
        this.totalScore += score;
    }

    public int getAverageScore(){
        return this.totalScore/this.courseNum;
    }

    @Override
    public int compareTo(Student o) {
        if(Integer.parseInt(this.getNumber()) > Integer.parseInt(o.getNumber()))
            return 1;
        else if (Integer.parseInt(this.getNumber()) < Integer.parseInt(o.getNumber())) {
            return -1;
        }
        return 0;
    }
}
class Course implements Comparable<Course>{
    //课程名字
    private String name;
    //考核方式
    private String testMode;

    private double usualRate;

    private double finalRate;

    private ArrayList<Double> rateList;

    private int scoreTotal = 0;

    private int usualScoreTotal = 0;

    private int finalScoreTotal = 0;
    //选课人数
    private int num = 0;


    public Course(String name, String testMode) {
        this.name = name;
        //是否必修
        this.testMode = testMode;
    }

    public Course(String name, String testMode, ArrayList<Double> rateList) {
        this.name = name;
        this.testMode = testMode;
        this.rateList = rateList;
    }

    public Course(String name, String testMode, double usualRate, double finalRate) {
        this.name = name;
        this.testMode = testMode;
        this.usualRate = usualRate;
        this.finalRate = finalRate;
    }

    public double getUsualRate() {
        return usualRate;
    }

    public double getFinalRate() {
        return finalRate;
    }

    public ArrayList<Double> getRateList() {
        return rateList;
    }

    public String getName() {
        return name;
    }


    public String getTestMode() {
        return testMode;
    }

    public boolean isExamRateLegal(){
        return this.finalRate + this.usualRate == 1;
    }

    public boolean isExperimentRateLegal(){
        double sum = 0;
        for(Double d : this.rateList){
            sum += d;
        }
        return sum == 1;
    }

    public void addExamScore(ExamScores score){
        this.finalScoreTotal += score.getFinalScore();
        this.usualScoreTotal += score.getUsualScore();
        this.scoreTotal += score.getScore();
        this.num += 1;
    }

    public void  addExamineScore(ExamineScores score){
        this.finalScoreTotal += score.getScore();
        this.scoreTotal += score.getScore();
        this.num += 1;
    }

    public void addExperimentScore(Experiment score){
        this.finalScoreTotal += score.getScore();
        this.scoreTotal += score.getScore();
        this.num += 1;
    }

    public int getAverageScore(){
        return this.scoreTotal/num;
    }

    public int getAverageUsualScore(){
        return this.usualScoreTotal/num;
    }

    public int getAverageFinalScore(){
        return this.finalScoreTotal/num;
    }

    @Override
    public int compareTo(Course o) {
        Collator instance = Collator.getInstance(Locale.CHINA);

        return instance.compare(this.name,o.getName());
    }
}
abstract class Score implements Comparable<Score>{

    public Score() {
    }
    public abstract int getScore();
}
class Experiment extends Score{
    ArrayList<Integer> scores = new ArrayList<>();
    ArrayList<Double> rateList;


    public Experiment() {
    }

    public void addAExperimentScore(int score){
        this.scores.add(score);
    }

    public void setRateList(ArrayList<Double> rateList) {
        this.rateList = rateList;
    }

    @Override
    public int getScore() {
        double totalScore = 0;
        for(int i = 0 ; i < scores.size() ; i++){
            totalScore += scores.get(i) * rateList.get(i);
        }

        return (int)totalScore;
    }

    @Override
    public int compareTo(Score o) {
        return Integer.compare(this.getScore(),o.getScore());
    }
}
class ExamineScores extends Score{//考察成绩
    private int finalScore;

    public  ExamineScores(int finalScore){
        this.finalScore = finalScore;
    }


    @Override
    public int getScore() {
        return this.finalScore;
    }

    @Override
    public int compareTo(Score o) {
        if(this.getScore() > o.getScore())
            return -1;
        else if(this.getScore() < o.getScore())
            return 1;
        return 0;
    }
}
class ExamScores extends Score{//考试成绩
    private int usualScore;
    private int finalScore;
    private double usualRate;
    private double finalRate;


    public ExamScores(int usualScore, int finalScore) {
        this.usualScore = usualScore;
        this.finalScore = finalScore;
        this.usualRate = 0.3;
        this.finalRate = 0.7;

    }

    public void setUsualRate(double usualRate) {
        this.usualRate = usualRate;
    }

    public void setFinalRate(double finalRate) {
        this.finalRate = finalRate;
    }

    public int getUsualScore() {
        return usualScore;
    }


    public int getFinalScore() {
        return finalScore;
    }


    @Override
    public int getScore() {
        return (int)(usualScore * usualRate + finalScore * finalRate);
    }

    @Override
    public int compareTo(Score o) {
        if(this.getScore() > o.getScore())
            return -1;
        else if(this.getScore() < o.getScore())
            return 1;
        return 0;
    }
}
class CourseSelection implements Comparable<CourseSelection>{
    private Course course;
    private Student student;
    private Score score;


    public CourseSelection(Course course, Student student, Score score) {
        this.course = course;
        this.student = student;
        this.score = score;
    }

    public Course getCourse() {
        return course;
    }


    public Student getStudent() {
        return student;
    }



    public Score getScore() {
        return score;
    }


    @Override
    public int compareTo(CourseSelection o) {
        if(Integer.parseInt(this.student.getNumber()) > Integer.parseInt(o.getStudent().getNumber()))
            return 1;
        else if(Integer.parseInt(this.student.getNumber()) < Integer.parseInt(o.getStudent().getNumber()))
            return -1;
        return this.score.compareTo(o.score);
    }
}

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

        接入Comparable接口并利用其进行排序即可

        源码如下:

 

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int n = Integer.parseInt(input.nextLine());
        ArrayList<IdCardNum> idCardNums = new ArrayList<>();
        while (n > 0){
            idCardNums.add(new IdCardNum(input.nextLine()));
            n--;
        }
        idCardNums.sort(Comparator.naturalOrder());
        boolean inputOver = false;
        while (!inputOver){
            String str = input.nextLine();
            if (str.matches("^sort2$")){
                for (IdCardNum idCardNum : idCardNums){
                    System.out.println(idCardNum.getNum());
                }
            } else if (str.matches("^sort1$")) {
                for (IdCardNum idCardNum : idCardNums){
                    System.out.println(idCardNum.getLocalDate());
                }
            } else if (str.matches("e")) {
                System.out.println("exit");
                inputOver = true;
            }else
                System.out.println("wrong format");
        }

    }
}
class IdCardNum implements Comparable<IdCardNum>{
    private String num;

    public IdCardNum() {
    }

    public IdCardNum(String num) {
        this.num = num;
    }

    public String getNum() {
        return num;
    }

    public LocalDate getLocalDate() {
        String date = this.getNum().substring(6,10) + "-" + this.getNum().substring(10,12) + "-" + this.getNum().substring(12,14);
        return LocalDate.parse(date);
    }

    @Override
    public int compareTo(IdCardNum o) {
        if(this.getLocalDate().isAfter(o.getLocalDate()))
            return 1;
        else if(this.getLocalDate().isBefore(o.getLocalDate()))
            return -1;
        else
            return 0;
    }
}

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

       熟悉接口的使用方法,以及有一定对栈的理解即可完成解答
       源码如下:
import java.util.*;

public class Main {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        ArrayIntegerStack stack = new ArrayIntegerStack(n);
        int m = input.nextInt();
        for(int i = 0 ; i < m ; i++){
            Integer item = input.nextInt();
            System.out.println(stack.push(item));
        }
        System.out.println(stack.peek() + "," + stack.empty() + "," + stack.size());
        System.out.println(Arrays.toString(stack.getIntegers()));
        int o = input.nextInt();
        for(int i = 0 ; i < o ; i++){
            System.out.println(stack.pop());
        }
        System.out.println(stack.peek() + "," + stack.empty() + "," + stack.size());
        System.out.println(Arrays.toString(stack.getIntegers()));
    }
}

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[] integers ;
    public int point;


    public ArrayIntegerStack(){
        this.integers = new Integer[0];
        this.point = -1;
    }

    public  ArrayIntegerStack(int n){
        this.integers = new Integer[n];
        this.point = -1;
    }

    public Integer[] getIntegers() {
        return integers;
    }

    @Override
    public Integer push(Integer item) {
        if(item == null)
            return null;
        if(this.size() == this.integers.length)
            return null;
        this.point += 1;
        this.integers[point] = item;
        return item;
    }

    @Override
    public Integer pop() {

        if (this.empty())
            return null;
        Integer integer = this.integers[point];
        point -= 1;
        return integer;
    }

    @Override
    public Integer peek() {

        if (this.empty())
            return null;
        return this.integers[point];
    }

    @Override
    public boolean empty() {
        return this.point < 0;
    }

    @Override
    public int size() {
        return point + 1;
    }
}

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

         理解Override的概念以及用法即可完成解答
        源码如下:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        ArrayList<PersonOverride> persons1 = new ArrayList<>();
        int n1 = input.nextInt();
        for (int i = 0 ; i < n1 ; i++){
            PersonOverride personOverride = new PersonOverride();
            persons1.add(personOverride);
        }
        ArrayList<PersonOverride> persons2 = new ArrayList<>();
        int n2 = input.nextInt();
        for (int i = 0 ; i < n2 ; i++){
            String name = input.next();
            int age = input.nextInt();
            boolean gender = input.nextBoolean();
            PersonOverride personOverride = new PersonOverride(name , age , gender);
            if(isNotRepeat(persons2, personOverride))
                persons2.add(personOverride);
        }
        for (PersonOverride personOverride : persons1){
            System.out.println(personOverride);
        }
        for (PersonOverride personOverride : persons2){
            System.out.println(personOverride);
        }
        System.out.println(persons2.size());
        System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));
    }
    public static boolean isNotRepeat(ArrayList<PersonOverride> persons , PersonOverride personOverride){
        if(persons.isEmpty())
            return true;
        for(PersonOverride personOverride1 : persons){
            if(personOverride1.equals(personOverride))
                return false;
        }
        return true;
    }

}
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;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public boolean isGender() {
        return gender;
    }

    @Override
    public boolean equals(Object o){
        return this.name.equals(((PersonOverride) o).getName()) && this.age == ((PersonOverride) o).getAge() && this.gender == ((PersonOverride) o).isGender();
    }

    @Override
    public String toString(){
        String str = this.name;
        str += "-";
        str += Integer.toString(this.age);
        str += "-";
        str += Boolean.toString(this.gender);
        return str;
    }

}

 3.踩坑心得

    在第一次的课程成绩统计系统中最开始并没有使用正则表达式对输入进行判断而是人为进行判断,导致许多非法输入难以去除,导致程序抛出异常  

     使用正则前:

       使用正则后:

 4.改进建议

    要多使用正则表达式对输入的数据,文本进行处理,尽量避免人为对数据判断,避免异常输入却没被考虑到的情况

      防止异常的产生。

5.总结

    通过这一阶段的学习,掌握了基本的面向对象的设计思路,思想。

  ···   掌握了接口,继承,多态等概念以及使用运用方法

      掌握了程序设计七大原则

      掌握了使用异常编写程序的方法

      掌握了正则表达式的使用,能运用正则表达式对文本进行处理

 

 建议

     可以增加边讲边练的部分,感觉在课上写代码更容易掌握所学的内容

 

 

 

posted @ 2023-06-27 22:13  22201201-陈柏艺  阅读(42)  评论(0)    收藏  举报