首页 > 其他分享 >Blog - 2

Blog - 2

时间:2023-06-29 21:11:06浏览次数:30  
标签:strs int orders Blog record && public

前言

题目量和难度

我觉得觉得作业题量适中,不会太多也不会太少,能让我练习。这次大作业,一共三道题。第一题和第三题难度不大,但是第二题是点菜系列的题目,这道题占了70分,而我只拿到了60分。在期中考中,虽然有三道题,但难度不算太大,每一道题都是在前一道题的基础上稍加修改即可。实验一只有两道题,一道是自己写程序,一道是修改已给出的代码。个人感觉第二道题比第一道题要稍微难一点,因为要先理解已给出的代码还要在此基础上修改。对于刚学不久java的我来说,给别人代码改错属实是有点难改了。但总体来说,实验难度不会像作业那么大,都能完整地做完题目,并且给的时间也充裕。

知识点

  1. 正则表达式的运用
  2. 类的设计及其方法的调用
  3. 继承与多态和容器类的问题
  4. 类的构造方法
  5. 方法的调用
  6. 参数传递
  7. 对象的构造与使用
  8. 循环结构、控制结构
  9. 方法重载
  10. private、protected、public等关键的使用场合与使用方法、方法调用时引用类型参数的传递过程

设计与分析

习题四

代码

  1 import java.util.Scanner;
  2 import java.util.Calendar;
  3 import java.util.Date;
  4 import java.util.InputMismatchException;
  5 import java.text.ParseException;
  6 import java.text.SimpleDateFormat;
  7 import java.util.regex.Pattern;
  8 
  9 public class Main {
 10     
 11     public static void main(String args[]) throws ParseException {
 12         Scanner input=new Scanner(System.in);
 13         boolean tableError[]=new boolean[56];
 14         for(int i=0;i<56;i++) {
 15             tableError[i]=false;
 16         }
 17         int error=0;
 18         //数据
 19         String dishName="";
 20         int unit_price=0;
 21         int num;
 22         int portion;
 23         String tableNum="";
 24         int orderNum = 0;
 25         Menu menu=new Menu();
 26         Order[] orders=new Order[100];
 27         Date orderTime=new Date();
 28         String time;
 29         String unit_price1;
 30         SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");
 31         format.setLenient(false);
 32 
 33     
 34         while(!dishName.equals("end")) {
 35             while(true) {
 36                 if(dishName.equals("")) dishName=input.next();
 37                 if(dishName.equals("end")) break;
 38                 if(!isNumber(dishName)&&!dishName.equals("table")) {
 39                     unit_price1=input.next();
 40                     if(!isNumber(unit_price1)||unit_price1.charAt(0)=='0') {
 41                         System.out.println("wrong format");
 42                         dishName=input.next();
 43                         dishName=input.nextLine();
 44                         for(int i=0;i<100;i++) {
 45                             if(orders[i]==null) {
 46                                 error=i;
 47                                 break;
 48                             }
 49                         }
 50                         tableError[error]=true;
 51                         break;
 52                     }
 53                     unit_price=Integer.parseInt(unit_price1);
 54                     if(unit_price>=400||unit_price<=0) {
 55                         System.out.println(dishName + " price out of range " + unit_price);
 56                         dishName=input.next();
 57                         continue;
 58                     }
 59                     if(menu.searthDish(dishName)==null)
 60                         menu.addDish(dishName, unit_price);    
 61                     else {
 62                         Dish mid=menu.searthDish(dishName);
 63                         mid.name=dishName;
 64                         mid.unit_price=unit_price;
 65                     }
 66                         
 67                     dishName=input.next();
 68                     if(dishName.equals("T")) {
 69                         for(int i=0;i<100;i++) {
 70                             if(menu.dishs[i+1]==null) {
 71                                 menu.dishs[i].special=true;
 72                                 dishName=input.next();    
 73                                 break;
 74                         }
 75                     }
 76                     continue;
 77                     }
 78                 }
 79                 if(dishName.equals("table")) {
 80                     for(int i=0;i<100;i++) {
 81                         if(orders[i]==null) {
 82                             error=i;
 83                             break;
 84                         }
 85                     }
 86                     tableNum=input.next();
 87                     time=input.nextLine();
 88                     //String times[]=new String[4];
 89                     if(time.charAt(5)!='/' ) {
 90                         //times=time.split(" ");
 91                         //time=" " + times[2] + " " + times[3];
 92                         System.out.println("wrong format");
 93                         tableError[error]=true;
 94                         break;
 95                     }
 96                     
 97                     String deal[]=new String[3];
 98                     String deal2[]=new String[3];
 99                     String a1[]=new String[2];
100                     a1=time.split(" ");
101                     deal=a1[1].split("/");
102                     deal2=a1[2].split("/");
103                     
104                     if(deal[0].length()!=4) {
105                         System.out.print("wrong format");
106                         tableError[error]=true;
107                         break;
108                     }
109                     else {
110                         for(int x=0;x<3;x++) {
111                             if(deal2[x].length()>2||(x>0&&deal[x].length()>2)) {
112                                 System.out.print("wrong format");
113                                 tableError[error]=true;
114                                 break;
115                             }
116                             if(deal2[x].length()==1) {
117                                 deal2[x]="0"+deal2[x];
118                             }
119                             if(deal[x].length()==1&&x>0) {
120                                 deal2[x]="0"+deal2[x];
121                             }
122                         }
123                         if(tableError[error]) break;
124 
125                         time="";
126                         for(int i=0;i<6;i++) {
127                             if(i<2) {
128                                 time+=deal[i] + '/';
129                             }
130                             if(i==2) {
131                                 time+=deal[i] + " ";
132                             }
133                             if(i>=3&&i<5) {
134                                 time+=deal2[i-3] + '/';
135                             }
136                             if(i==5) {
137                                 time+=deal2[i-3];
138                             }
139                         }
140                     }
141                     try {
142                         orderTime=format.parse(time);
143                     } catch (ParseException e) {
144                         System.out.println(tableNum + " date error");
145                         tableError[error]=true;
146                         break;
147                     }
148                     String startDateStr = "2022/01/01 00/00/00";
149                     String endDateStr = "2024/01/01 00/00/00";
150 
151                     Date startDate = format.parse(startDateStr);
152                     Date endDate = format.parse(endDateStr);
153 
154                     if (!(orderTime.after(startDate) && orderTime.before(endDate))) {
155                         System.out.println("not a valid time period");
156                         tableError[error]=true;
157                         break;
158                     }
159                     if(!stringIsNumber(tableNum)||((tableNum.charAt(0)=='0')&&tableNum.length()>1)) {
160                         System.out.println("wrong format");
161                         tableError[error]=true;
162                         break;
163                     }
164                     if(stringIsNumber(tableNum)&&(Integer.parseInt(tableNum)>55||Integer.parseInt(tableNum)<1)) {
165                         System.out.println(tableNum + " table num out of range");
166                         tableError[error]=true;
167                         break;
168                     }
169                     if(!isBusinessTime(orderTime)) {
170                         System.out.println("table " + tableNum + " out of opening hours");
171                         tableError[error]=true;
172                         break;
173                     }
174                     System.out.println("table " + tableNum + ": ");
175                     break;
176                 }
177             }
178             boolean numError=false;
179             boolean portionError=false;
180             boolean flag=false;
181             int index=0;
182             while(true) {//开始处理订单里面的点菜记录
183                 String temp;
184                 String orderNum1;
185                 orderNum1=input.next();
186                 if(orderNum1.equals("T")) {
187                     orderNum1=input.next();
188                 }
189                 if(orderNum1.equals("end"))  {
190                     dishName="end";
191                     break;
192                 }
193                 if(orderNum1.equals("table")) {
194                     orderNum=0;
195                     dishName="table";
196                     flag=false;
197                     break;
198                 }
199                 if(!isNumber(orderNum1)&&!tableError[error]) {
200                     System.out.println("invalid dish");
201                     orderNum1=input.next();
202                     continue;
203                 }
204                 else if(!isNumber(orderNum1)&&tableError[error]) {
205                     orderNum1=input.next();
206                     continue;
207                 }
208                 
209 
210                 temp=input.next();
211                 if(orderNum>Integer.parseInt(orderNum1)&&!tableError[error]&&!portionError&&!temp.equals("delete")) {
212                     System.out.println("record serial number sequence error");
213                     numError=true;
214                 }
215                 if(orderNum1.charAt(0)=='0') {
216                     System.out.println("wrong format");
217                     portion=input.nextInt();
218                     num=input.nextInt();
219                     continue;
220                 }
221                 orderNum=Integer.parseInt(orderNum1);
222                 if(!isNumber(temp)) {//不是数字,说明要么是删除,要么是菜名
223                     if(!temp.equals("delete")) {//判断是否删除
224                         dishName=temp;
225                         portion=input.nextInt();
226                         num=input.nextInt();
227                         if(menu.searthDish(dishName)==null&&!tableError[error]) {
228                             System.out.println(dishName + " does not exist");
229                             orderNum=0;
230                             continue;
231                         }
232                         
233                         else if(portion>=4&&!tableError[error]) {
234                             System.out.println(orderNum + " portion out of range " + portion);
235                             portionError=true;
236                         }
237                         else if(num>=16&&!tableError[error]) {
238                             System.out.println(orderNum + " num out of range " + num);
239                             orderNum=0;
240                         }
241                         for(int i=0;true;i++) {//new一个Order对象第一次储存某一桌的订单
242                             if(orders[i]==null&&!flag) {
243                                 orders[i]=new Order();
244                                 Record fim=orders[i].addRecord(orderNum, dishName, portion, num);
245                                 for(int s=0;menu.dishs[s]!=null;s++) {
246                                     if(dishName.equals(menu.dishs[s].name)) {
247                                         if(portion<4&&num<16&&!tableError[i]) {
248                                             fim.dish=menu.searthDish(dishName);
249                                             System.out.println(orderNum + " " + dishName + " " + fim.getPrice());
250                                         }
251                                         orders[i].tableNum=tableNum;
252                                         orders[i].orderTime=orderTime;
253                                         
254                                         index=i;
255                                         flag=true;
256                                         break;
257                                     }
258                                     if(menu.dishs[s+1]==null) {
259                                         orders[i].tableNum=tableNum;
260                                         orders[i].orderTime=orderTime;
261                                         index=i;
262                                         flag=true;
263                                         if(!tableError[i])
264                                             System.out.println(dishName + " does not exist");
265                                     }
266                                 }
267                                 break;
268                             }
269                             
270                             if(flag&&!numError) {
271                                 Record fim=orders[index].addRecord(orderNum, dishName, portion, num);
272                                 for(int s=0;menu.dishs[s]!=null;s++) {
273                                     if(dishName.equals(menu.dishs[s].name)) {
274                                         if(portion<4&&num<16&&!tableError[index]) {
275                                             fim.dish=menu.searthDish(dishName);
276                                             System.out.println(orderNum + " " + dishName + " " + fim.getPrice());
277                                         }
278                                         orders[index].tableNum=tableNum;
279                                         break;
280                                     }
281                                     if(menu.dishs[s+1]==null) {
282                                         if(!tableError[index])
283                                             System.out.println(dishName + " does not exist");
284                                     }
285                                 }
286                                 break;
287                                 
288                             }
289                             if(numError) {
290                                 break;
291                             }
292                         }
293                     }
294                     else {//删除
295                         for(int i=0;orders[i]!=null;i++) {
296                             if(orders[i+1]==null&&!tableError[error]) {
297                                 switch(orders[i].delRecordByOrderNum(orderNum)) {
298                                 case 1:break;
299                                 case -1:System.out.println("deduplication " + orderNum);
300                                     break;
301                                 case 0:System.out.println("delete error;");
302                                     break;
303                                 default:
304                                     break;
305                                 }
306                             }
307                         }
308                     }
309                 }
310                 else {//是数字的话说明是代点菜
311                     tableNum=temp;
312                     dishName=input.next();
313                     portion=input.nextInt();
314                     num=input.nextInt();
315                     for(int i=0;orders[i]!=null;i++) {//
316                         if(orders[i+1]==null) {
317                             Record dis=orders[i].addNewRecord( Integer.parseInt(temp), dishName, portion, num);
318                             for(int e=0;e<100;e++) {
319                                 if(menu.dishs[e].name.equals(dis.dish.name)) {
320                                     for(int f=0;orders[f]!=null;f++) {
321                                         if(orders[f].tableNum.equals(orderNum)) {
322                                             dis.dish=menu.dishs[e];
323                                             System.out.println(temp + " table " + orders[index].tableNum + " pay for table " + orderNum + " " + dis.dish.getPrice(portion));
324                                         }
325                                         if(orders[f+1]==null) {
326                                             System.out.println("Table number :" + orderNum + " does not exist");
327                                             orderNum=0;
328                                         }
329                                     }
330                                     break;
331                                 }
332                             }
333                             break;
334                         }
335                     }
336                 }
337             }
338             
339         }
340         for(int i=0;i<100;i++) {
341             if(orders[i]!=null&&!tableError[i]) {
342                 System.out.println("table " + orders[i].tableNum + ": " + orders[i].getInitialPrice() + " " + orders[i].getTotalPrice());
343             }
344         }
345         input.close();
346     }
347     
348     
349     
350     
351 
352     public static boolean isNumber(String str){
353         for (int i = str.length();--i>=0;){  
354             if (!Character.isDigit(str.charAt(i))){
355                 return false;
356             }
357         }
358         return true;
359      }
360     
361     public static boolean stringIsNumber(String str) {
362         Pattern pattern = Pattern.compile("^\\d+$");
363         return pattern.matcher(str).matches();
364     }
365     public static boolean isBusinessTime(Date date) {
366         Calendar calendar = Calendar.getInstance();
367         calendar.setTime(date);
368 
369         // 获取当前日期时间的星期几
370         int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
371 
372         // 判断是否在周一至周五营业时间内
373         if (dayOfWeek >= Calendar.MONDAY && dayOfWeek <= Calendar.FRIDAY) {
374             // 获取当前日期时间的小时数和分钟数
375             int hour = calendar.get(Calendar.HOUR_OF_DAY);
376             int minute = calendar.get(Calendar.MINUTE);
377 
378             // 判断是否在中午和晚上营业时间内
379             if ((hour >= 10 && hour < 14) || (hour == 14 && minute <= 30) || (hour >= 17 && hour < 20) || (hour == 20 && minute <= 30)) {
380                 return true;
381             }
382         }
383         // 判断是否在周末营业时间内
384         else if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
385             // 获取当前日期时间的小时数和分钟数
386             int hour = calendar.get(Calendar.HOUR_OF_DAY);
387             int minute = calendar.get(Calendar.MINUTE);
388 
389             // 判断是否在周末营业时间内
390             if (hour >= 9 && hour < 21) {
391                 return true;
392             }
393             else if (hour == 21 && minute <= 30) {
394                 return true;
395             }
396         }
397 
398         // 如果不在营业时间内,则返回false
399         return false;
400     }
401 }
402 
403  class Dish {
404     
405     String name;//菜品名称
406     int unit_price; //单价
407     boolean special=false;
408     int getPrice(int portion){
409         switch(portion) {
410         case 1: return unit_price;
411         case 2: return (int)(unit_price*1.5f+0.5f);
412         case 3: return (int)(unit_price*2);
413         }
414         return unit_price;
415     }//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份) 
416 
417 } 
418 class Menu {
419 
420     Dish[] dishs=new Dish[100];    //菜品数组,保存所有菜品信息
421     Dish searthDish(String dishName){
422         for(Dish dish:dishs) {
423             if(dish==null) break;
424             if(dish.name.equals(dishName)) return dish;
425         }
426         return null;
427     }        //根据菜名在菜谱中查找菜品信息,返回Dish对象。
428     Dish addDish(String dishName,int unit_price) {
429         for(int i=0;i<100;i++) {
430             if(dishs[i]==null) {
431                 dishs[i]=new Dish();
432                 dishs[i].name=dishName;
433                 dishs[i].unit_price=unit_price;
434                 return dishs[i];
435             }
436         }
437         return null;//添加失败返回null
438     }        //添加一道菜品信息
439 
440 }
441 class Order {
442     
443     String tableNum;
444 
445     Record[] records=new Record[100];    //保存订单上每一道的记录
446     Record[] newRecord=new Record[100];
447     java.util.Date orderTime=new java.util.Date();
448     
449     int getTotalPrice() {
450         Calendar calendar = Calendar.getInstance();
451         calendar.setTime(orderTime);
452         int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // 获取星期几
453         int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 获取小时数
454 
455         int sum=0;
456         
457         for(int i=0;records[i]!=null;i++) {
458             if(records[i].orderNum>0) {
459                 if (dayOfWeek >= Calendar.MONDAY && dayOfWeek <= Calendar.FRIDAY&& hourOfDay >= 10 && hourOfDay < 14|| (hourOfDay == 14 && calendar.get(Calendar.MINUTE) <= 30)) {
460                     if(records[i].dish.special) sum+=(int)(records[i].getPrice()*0.7f+0.5f);
461                     else sum+=(int)(records[i].getPrice()*0.6f+0.5f);
462                 }
463                 else if (dayOfWeek >= 2 && dayOfWeek <= 6 && hourOfDay >= 17 && hourOfDay < 20 || hourOfDay == 20 && calendar.get(Calendar.MINUTE) <= 30) {
464                     if(records[i].dish.special) sum+=(int)(records[i].getPrice()*0.7f+0.5f);
465                     else sum+=(int)(records[i].getPrice()*0.8f+0.5f);
466                 }
467                 else if ((dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) && hourOfDay >= 9 && hourOfDay < 21 || hourOfDay == 21 && calendar.get(Calendar.MINUTE) <= 30) {
468                     sum+=records[i].getPrice();
469                 }
470             }
471         }
472         for(int i=0;newRecord[i]!=null;i++) {
473             if (dayOfWeek >= Calendar.MONDAY && dayOfWeek <= Calendar.FRIDAY&& hourOfDay >= 10 && hourOfDay < 14|| (hourOfDay == 14 && calendar.get(Calendar.MINUTE) <= 30)) {
474                 if(newRecord[i].dish.special) sum+=(int)(newRecord[i].getPrice()*0.7f+0.5f);
475                 else sum+=(int)(newRecord[i].getPrice()*0.6f+0.5f);
476             }
477             else if (dayOfWeek >= 2 && dayOfWeek <= 6 && hourOfDay >= 17 && hourOfDay < 20 || hourOfDay == 20 && calendar.get(Calendar.MINUTE) <= 30) {
478                 if(newRecord[i].dish.special) sum+=(int)(newRecord[i].getPrice()*0.7f+0.5f);
479                 else sum+=(int)(newRecord[i].getPrice()*0.8f+0.5f);
480             }
481             else if ((dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) && hourOfDay >= 9 && hourOfDay < 21 || hourOfDay == 21 && calendar.get(Calendar.MINUTE) <= 30) {
482                 sum+=newRecord[i].getPrice();
483             }
484         }
485         return sum;
486     }        //计算订单的总价(折扣后)
487     int getInitialPrice() {
488         int sum=0;
489         for(int i=0;records[i]!=null;i++) {
490             if(records[i].orderNum>0)
491                 sum+=records[i].getPrice();
492         }
493         for(int i=0;newRecord[i]!=null;i++) {
494             sum+=newRecord[i].getPrice();
495         }
496         return sum;
497     }
498     Record addRecord(int orderNum,String dishName,int portion,int num) {
499         for(int i=0;i<100;i++) {
500             if(records[i]==null) {
501                 records[i]=new Record();
502                 records[i].dish.name=dishName;
503                 records[i].orderNum=orderNum;
504                 records[i].portion=portion;
505                 records[i].num=num;
506                 return records[i];
507             }
508         }
509         return null;
510     }        //添加一条菜品信息到订单中。
511     int delRecordByOrderNum(int orderNum) {
512         int i;
513         for(i=0;records[i]!=null;i++) {
514             if(records[i].orderNum==orderNum) {
515                 records[i].orderNum=-orderNum;
516                 return 1;
517             }
518             if(records[i].orderNum==-orderNum) {
519                 return -1;
520             }
521         }
522         if(records[i]==null) {
523             return 0;
524         }
525         return i;
526     }            //根据序号删除一条记录
527     
528     void addTableNum(String tableNum) {
529         this.tableNum=tableNum;
530     }
531     Record findRecordByNum(int orderNum) {
532         for(Record record:records) {
533             if(record.orderNum==orderNum) {
534                 return record;
535             }
536         }
537         return null;
538     }        //根据序号查找一条记录
539     
540     Record addNewRecord(int orderNum,String dishName,int portion,int num) {
541         for(int i=0;i<100;i++) {
542             if(newRecord[i]==null) {
543                 newRecord[i]=new Record();
544                 newRecord[i].dish.name=dishName;
545                 newRecord[i].orderNum=orderNum;
546                 newRecord[i].portion=portion;
547                 newRecord[i].num=num;
548                 return newRecord[i];
549             }
550         }
551         return null;
552     }
553     
554 }
555 class Record {
556 
557     int orderNum;    //序号
558     Dish dish=new Dish();    //菜品
559     int portion;    //份额(1/2/3代表小/中/大份)
560     int num;    //份数
561     int getPrice() {
562         return dish.getPrice(portion)*num;
563     }        //计价,计算本条记录的价格
564 
565 }

 Record 

它有四个字段:orderNumdishportion 和 numorderNum 字段是一个整数,表示订单号。dish 字段是 Dish 类的一个实例。portion 字段是一个整数,表示份量大小,其中 1、2 和 3 分别代表小、中和大份。num 字段是一个整数,表示份数。

该类还有一个名为 getPrice() 的方法,它通过调用 Dish 对象的 getPrice() 方法来计算记录的价格,并将 portion 字段的值作为参数传入。然后将结果乘以 num 字段的值以获得最终价格。

Order

该类有几个实例变量,包括 tableNum(一个 String),records 和 newRecordRecord 对象的数组)以及 orderTime(一个 java.util.Date 对象)。该类还有几个方法,包括 getTotalPrice()(计算订单的总价(折扣后)),getInitialPrice()(计算订单的初始价格(不打折)),addRecord()(向订单中添加一条新记录),delRecordByOrderNum()(根据序号从订单中删除一条记录),addTableNum()(为订单设置桌号),findRecordByNum()(根据序号在订单中查找一条记录)和 addNewRecord()(向订单中添加一条新记录)。

Menu 

它有一个名为 dishs 的字段,它是一个 Dish 类型的数组,用于保存所有菜品信息。

该类还有两个方法:searthDish() 和 addDish()searthDish() 方法接受一个字符串参数 dishName,表示要查找的菜品名称。该方法遍历 dishs 数组,如果找到一个 Dish 对象的 name 字段与传入的 dishName 参数相同,则返回该 Dish 对象。如果遍历完整个数组都没有找到匹配的菜品,则返回 null

addDish() 方法接受两个参数:一个字符串参数 dishName 和一个整数参数 unit_price。该方法遍历 dishs 数组,找到第一个为 null 的元素,并在该位置创建一个新的 Dish 对象。然后将新创建的 Dish 对象的 name 字段设置为传入的 dishName 参数,将其 unit_price 字段设置为传入的 unit_price 参数,并返回新创建的 Dish 对象。如果遍历完整个数组都没有找到空位,则返回 null 表示添加失败。

Dish

该类有几个实例变量,包括 name(菜品名称,一个 String),unit_price(单价,一个 int)和 special(一个布尔值,表示菜品是否特殊)。该类还有一个方法 getPrice(),它根据点菜的份额(输入数据只能是 1/2/3,代表小/中/大份)来计算菜品的价格。

三个静态方法

 

第一个静态方法 isNumber(String str) 接受一个字符串作为参数,然后遍历字符串中的每个字符,检查它们是否都是数字。如果都是数字,则返回 true;否则返回 false

 

第二个方法 stringIsNumber(String str) 也接受一个字符串作为参数,然后使用正则表达式来检查字符串是否只包含数字。如果是,则返回 true;否则返回 false

 

第三个方法 isBusinessTime(Date date) 接受一个日期时间对象作为参数,然后使用 Calendar 类来获取日期时间的星期几、小时数和分钟数。接着,该方法判断日期时间是否在周一至周五的营业时间内(中午 10 点至下午 2 点半或下午 5 点至晚上 8 点半),或者是否在周末的营业时间内(早上 9 点至晚上 9 点半)。如果在营业时间内,则返回 true;否则返回 false

 

本题的难点在于处理各种异常情况,如菜谱信息与订单信息混合、桌号所带时间格式合法但数据非法、同一桌菜名、份额相同的点菜记录要合并成一条进行计算等。此外,本题还增加了特色菜的功能,特色菜的输入格式为:菜品名+英文空格+基础价格+“T”。只要代码逻辑严密即可轻松应对。

UML

 习题五

代码

  1 import java.util.*;
  2 import java.util.regex.*;
  3 import java.text.*;
  4 
  5 public class Main {
  6     public static void main(String[] args) throws ParseException {
  7         Scanner sc = new Scanner(System.in);
  8         Menu menu = new Menu();
  9         Order[] orders = new Order[1000];
 10         Record[] recordss = new Record[1000];
 11         int t = 0, r = 0, c = 0;
 12         String temp = null;
 13         while (true) {
 14             String s = sc.nextLine();
 15             String[] strs = s.split(" ");
 16             if (strs[0].equals("table")) {
 17                 temp = s;
 18                 break;
 19             } else {
 20                 try {
 21                     if (strs.length == 2) {
 22                         if (menu.searthDish(strs[0]) != null)
 23                             menu.updateDish(strs[0], null, Integer.valueOf(strs[1]), null);
 24                         else menu.addDish(strs[0], null, Integer.valueOf(strs[1]), null);
 25                     } else if (strs.length == 4) {
 26                         if (menu.searthDish(strs[0]) != null)
 27                             menu.updateDish(strs[0], strs[1], Integer.valueOf(strs[2]), strs[3]);
 28                         else menu.addDish(strs[0], strs[1], Integer.valueOf(strs[2]), strs[3]);
 29                     } else {
 30                         System.out.println("wrong format");
 31                     }
 32                 } catch(Exception e) {
 33                     System.out.println("wrong format");
 34                 }
 35             }
 36         }
 37         String[] oneStrs = temp.split(" ");
 38         Pattern pattern = Pattern.compile("[0-9]*");
 39         Matcher isNum = pattern.matcher(oneStrs[1]);
 40         boolean wrongFlag = false;
 41         if (isNum.matches()) {
 42             orders[t++] = new Order(Integer.valueOf(oneStrs[1]), oneStrs[3], oneStrs[4], oneStrs[5], oneStrs[6]);
 43             orders[0].setMenu(menu);
 44         } else {
 45             wrongFlag = true;
 46             orders[t++] = new Order(-1, oneStrs[3], oneStrs[4], oneStrs[5], oneStrs[6]);
 47             orders[0].setMenu(null);
 48         }
 49         String phoneCon = "180、181、189、133、135、136";
 50         if (oneStrs[3].length() > 10 || oneStrs[4].length() != 11 || !phoneCon.contains(oneStrs[4].substring(0, 3))) {
 51             wrongFlag = true;
 52             orders[0].setMenu(null);
 53         }
 54         if (wrongFlag) {
 55             System.out.print("wrong format");
 56         }
 57         if (isAvailable(dateToWeek(oneStrs[5]), oneStrs[6]) == 0) {
 58             if (wrongFlag) {
 59                 System.out.println();
 60             }
 61             System.out.println("table " + oneStrs[1] + " out of opening hours");
 62             orders[0].setMenu(null);
 63         }
 64         if (orders[0].menu != null) {
 65             System.out.println("table " + oneStrs[1] + ": ");
 66         }
 67         while (true) {
 68             String s = sc.nextLine();
 69             String[] strs = s.split(" ");
 70             if (s.equals("end")) {
 71                 if (t == 0) return;
 72                 else break;
 73             } else {
 74                 if (strs[0].equals("table")) {
 75                     isNum = pattern.matcher(strs[1]);
 76                     if (wrongFlag) {
 77                         System.out.println();
 78                     }
 79                     wrongFlag = false;
 80                     if (isNum.matches()) {
 81                         orders[t++] = new Order(Integer.valueOf(strs[1]), strs[3], strs[4], strs[5], strs[6]);
 82                         orders[t - 1].setMenu(menu);
 83                     } else {
 84                         wrongFlag = true;
 85                         orders[t++] = new Order(-1, strs[3], strs[4], strs[5], strs[6]);
 86                         orders[t - 1].setMenu(null);
 87                     }
 88                     if (strs[3].length() > 10 || strs[4].length() != 11 || !phoneCon.contains(strs[4].substring(0, 3))) {
 89                         wrongFlag = true;
 90                         orders[t - 1].setMenu(null);
 91                     }
 92                     if (wrongFlag) {
 93                         System.out.print("wrong format");
 94                     }
 95                     if (isAvailable(dateToWeek(strs[5]), strs[6]) == 0) {
 96                         System.out.println("table " + strs[1] + " out of opening hours");
 97                         orders[t - 1].setMenu(null);
 98                     }
 99                     if (orders[t - 1].menu != null) {
100                         System.out.println("table " + strs[1] + ": ");
101                     }
102                     r = 0;
103                 } else {
104                     if (orders[t - 1].menu != null) {
105                         try {
106                             boolean flag = false, replaceFlag = false;
107                             if (strs.length == 5)
108                                 flag = orders[t - 1].addRecord(Integer.valueOf(strs[0]), strs[1], Integer.valueOf(strs[2]), Integer.valueOf(strs[3]), Integer.valueOf(strs[4]), null);
109                             else if (strs.length == 4)
110                                 flag = orders[t - 1].addRecord(Integer.valueOf(strs[0]), strs[1], null, Integer.valueOf(strs[2]), Integer.valueOf(strs[3]), null);
111                             else if (strs.length == 6) {
112                                 replaceFlag = true;
113                                 flag = orders[t - 1].addRecord(Integer.valueOf(strs[0]), strs[2], Integer.valueOf(strs[3]), Integer.valueOf(strs[4]), Integer.valueOf(strs[5]), new Replace(Integer.valueOf(orders[t - 1].orderNum), Integer.valueOf(strs[1])));
114                             } else if (strs.length == 2) {
115                                 orders[t - 1].deleteRecord(Integer.valueOf(strs[0]));
116                                 continue;
117                             } else {
118                                 System.out.println("wrong format");
119                             }
120                             if (flag) {
121                                 if (replaceFlag)
122                                     System.out.println(strs[0] + " table " + orders[t - 1].orderNum + " pay for table " + strs[1] + " " + orders[t - 1].records.get(r++).getPrice());
123                                 else
124                                     System.out.println(strs[0] + " " + strs[1] + " " + orders[t - 1].records.get(r++).getPrice());
125                             }
126                         } catch(Exception e) {
127                             System.out.println("wrong format");
128                         }
129                     }
130                 }
131             }
132         }
133         int count = 0;
134         while (orders[count] != null) {
135             if (orders[count].menu != null) {
136                 int sum = 0;
137                 int sumDiscount = 0;
138                 for (Record record : orders[count].records) {
139                     sum += record.getPrice();
140                     sumDiscount += record.getDiscountPrice(isAvailable(dateToWeek(orders[count].day), orders[count].time));
141                     if (record.getReplace() != null) {
142                         recordss[c++] = record;
143                     }
144                 }
145                 orders[count].sum = sum;
146                 orders[count].sumDiscount = sumDiscount;
147             }
148             count++;
149         }
150         count = 0;
151         TreeMap<String, Integer> map = new TreeMap<>();
152         while (orders[count] != null) {
153             if (orders[count].menu != null) {
154                 int sumTaste1 = 0, sumTaste2 = 0, sumTaste3 = 0;
155                 int n1 = 0, n2 = 0, n3 = 0;
156                 int nn1 = 0, nn2 = 0, nn3 = 0;
157                 for (Record record : orders[count].records) {
158                     if (record.getSpicy() != null) {
159                         if ("川菜".equals(record.getDish().getType())) {
160                             n1++;
161                             nn1 += record.getNum();
162                             sumTaste1 += record.getSpicy() * record.getNum();
163                         }
164                         if ("晋菜".equals(record.getDish().getType())) {
165                             n2++;
166                             nn2 += record.getNum();
167                             sumTaste2 += record.getSpicy() * record.getNum();
168                         }
169                         if ("浙菜".equals(record.getDish().getType())) {
170                             n3++;
171                             nn3 += record.getNum();
172                             sumTaste3 += record.getSpicy() * record.getNum();
173                         }
174                     }
175                 }
176                 if (count == 0 && wrongFlag) {
177                     System.out.println();
178                 }
179                 System.out.print("table " + orders[count].orderNum + ": " + orders[count].sum + " " + orders[count].sumDiscount);
180                 for (Record record : recordss) {
181                     if (record != null) {
182                         if (record.getReplace().getOriginNum() - 1 == count) {
183                             if ("川菜".equals(record.getDish().getType())) {
184                                 n1--;
185                                 nn1 -= record.getNum();
186                                 sumTaste1 -= record.getSpicy() * record.getNum();
187                             }
188                             if ("晋菜".equals(record.getDish().getType())) {
189                                 n2--;
190                                 nn2 -= record.getNum();
191                                 sumTaste2 -= record.getSpicy() * record.getNum();
192                             }
193                             if ("浙菜".equals(record.getDish().getType())) {
194                                 n3--;
195                                 nn3 -= record.getNum();
196                                 sumTaste3 -= record.getSpicy() * record.getNum();
197                             }
198                         }
199                         if (record.getReplace().getReplaceNum() - 1 == count) {
200                             if ("川菜".equals(record.getDish().getType())) {
201                                 n1++;
202                                 nn1 += record.getNum();
203                                 sumTaste1 += record.getSpicy() * record.getNum();
204                             }
205                             if ("晋菜".equals(record.getDish().getType())) {
206                                 n2++;
207                                 nn2 += record.getNum();
208                                 sumTaste2 += record.getSpicy() * record.getNum();
209                             }
210                             if ("浙菜".equals(record.getDish().getType())) {
211                                 n3++;
212                                 nn3 += record.getNum();
213                                 sumTaste3 += record.getSpicy() * record.getNum();
214                             }
215                         }
216                     } else {
217                         break;
218                     }
219                 }
220                 String[] spicyArr = {"不辣", "微辣", "稍辣", "辣", "很辣", "爆辣"};
221                 String[] acidityArr = {"不酸", "微酸", "稍酸", "酸", "很酸"};
222                 String[] sweetnessArr = {"不甜", "微甜", "稍甜", "甜"};
223                 if (n1 != 0)
224                     System.out.print(" 川菜 " + nn1 + " " + spicyArr[(int) Math.round((double) sumTaste1 / nn1)]);
225                 if (n2 != 0)
226                     System.out.print(" 晋菜 " + nn2 + " " + acidityArr[(int) Math.round((double) sumTaste2 / nn2)]);
227                 if (n3 != 0)
228                     System.out.print(" 浙菜 " + nn3 + " " + sweetnessArr[(int) Math.round((double) sumTaste3 / nn3)]);
229                 if (n1 == 0 && n2 == 0 && n3 == 0) {
230                     System.out.print(" ");
231                 }
232                 System.out.println();
233                 if (map.containsKey(orders[count].customerName)) {
234                     map.put(orders[count].customerName, map.get(orders[count].customerName) + orders[count].sumDiscount);
235                 } else {
236                     map.put(orders[count].customerName, orders[count].sumDiscount);
237                 }
238             }
239             count++;
240         }
241         Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
242         while (it.hasNext()) {
243             String e = it.next().getKey();
244             String phoneNum = null;
245             count = 0;
246             while (orders[count] != null) {
247                 if (e.equals(orders[count].customerName)) {
248                     phoneNum = orders[count].customerPhone;
249                     break;
250                 }
251                 count++;
252             }
253             if (it.hasNext()) {
254                 System.out.println(e + " " + phoneNum + " " + map.get(e));
255             } else {
256                 System.out.print(e + " " + phoneNum + " " + map.get(e));
257             }
258         }
259     }
260 
261     public static int dateToWeek(String dateTime) {
262         // 将变量名 'sdf' 改为 'format'
263         SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
264         Calendar cal = Calendar.getInstance();
265         try {
266             cal.setTime(format.parse(dateTime));
267         } catch (ParseException ex) {
268             ex.printStackTrace();
269         }
270         // 将变量名 'w' 改为 'week'
271         int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
272         return week >= 0 ? week : 0;
273     }
274     public static int isAvailable(int weekDays, String timeNow) throws ParseException {
275         SimpleDateFormat sdf = new SimpleDateFormat("HH/mm/ss");
276         long time = sdf.parse(timeNow).getTime();
277         long startTime1 = sdf.parse("10/30/00").getTime();
278         long endTime1 = sdf.parse("14/30/00").getTime();
279         long startTime2 = sdf.parse("17/00/00").getTime();
280         long endTime2 = sdf.parse("20/30/00").getTime();
281         if (weekDays == 6 || weekDays == 7) {
282             long startTime = sdf.parse("09/30/00").getTime();
283             long endTime = sdf.parse("21/30/00").getTime();
284             if (time >= startTime && time <= endTime) {
285                 return 3;
286             } else {
287                 return 0;
288             }
289         } else if (time >= startTime1 && time <= endTime1) {
290             return 1;
291         } else if (time >= startTime2 && time <= endTime2) {
292             return 2;
293         } else {
294             return 0;
295         }
296     }
297 }
298 
299 
300 class Dish {
301     private final String name;
302     private final String type;
303     private final int unitPrice;
304     private final boolean isVegetarian;
305 
306     public Dish(String name, String type, int unitPrice, boolean isVegetarian) {
307         this.name = name;
308         this.type = type;
309         this.unitPrice = unitPrice;
310         this.isVegetarian = isVegetarian;
311     }
312 
313     public String getName() {
314         return name;
315     }
316 
317     public String getType() {
318         return type;
319     }
320 
321     public int getUnitPrice() {
322         return unitPrice;
323     }
324 
325     public boolean isVegetarian() {
326         return isVegetarian;
327     }
328 
329     public int getPrice(int portion) {
330         switch (portion) {
331             case 1:
332                 return unitPrice;
333             case 2:
334                 return Math.round(unitPrice * 1.5f);
335             case 3:
336                 return unitPrice * 2;
337             default:
338                 throw new IllegalArgumentException("Invalid portion: " + portion);
339         }
340     }
341 }
342 
343 class Menu {
344     ArrayList<Dish> dishs = new ArrayList<>();//菜品数组,保存所有菜品信息
345 
346     Dish searthDish(String dishName) {
347         if (dishName != null) {
348             for (Dish dish : dishs) {
349                 if (dishName.equals(dish.getName())) {
350                     return dish;
351                 }
352             }
353             return null;
354         } else {
355             throw new RuntimeException("输入的菜品名称不能为空!");
356         }
357     }
358 
359     boolean updateDish(String dishName, String type, int unit_price, String special) {
360         if (dishName != null) {
361             for (int i = 0; i < dishs.size(); i++) {
362                 if (dishName.equals(dishs.get(i).getName())) {
363                     boolean flag = false;
364                     if (type != null && special != null && special.equals("T")) {
365                         flag = true;
366                     }
367                     dishs.set(i,new Dish(dishName, type, unit_price, flag));
368                     return true;
369                 }
370             }
371         }
372         return false;
373     }
374 
375     //添加一道菜品信息
376     Dish addDish(String dishName, String type, int unit_price, String special) {
377         boolean flag = (type != null && special != null && special.equals("T")) ? true : false;
378         Dish newDish = new Dish(dishName, type, unit_price, flag);
379         dishs.add(newDish);
380         return newDish;
381     }
382 }
383 
384 
385 class Record {
386     private final int recordNum;
387     private final Dish dish;
388     private final Integer spicy;
389     private final int portion;
390     private final int num;
391     private final Replace replace;
392 
393     public Record(int recordNum, Dish dish, Integer spicy, int portion, int num, Replace replace) {
394         this.recordNum = recordNum;
395         this.dish = dish;
396         this.spicy = spicy;
397         this.portion = portion;
398         this.num = num;
399         this.replace = replace;
400     }
401 
402     public int getRecordNum() {
403         return recordNum;
404     }
405 
406     public Dish getDish() {
407         return dish;
408     }
409 
410     public Integer getSpicy() {
411         return spicy;
412     }
413 
414     public int getPortion() {
415         return portion;
416     }
417 
418     public int getNum() {
419         return num;
420     }
421 
422     public Replace getReplace() {
423         return replace;
424     }
425 
426     public int getPrice() {
427         return dish.getPrice(portion) * num;
428     }
429 
430     public int getDiscountPrice(int discountType) {
431         switch (discountType) {
432             case 1:
433                 return dish.isVegetarian() ? (int) Math.round(dish.getPrice(portion) * num * 0.6)
434                         : (int) Math.round(dish.getPrice(portion) * num * 0.6);
435             case 2:
436                 return dish.isVegetarian() ? (int) Math.round(dish.getPrice(portion) * num * 0.8)
437                         : (int) Math.round(dish.getPrice(portion) * num * 0.8);
438             case 3:
439                 return dish.getPrice(portion) * num;
440             default:
441                 throw new RuntimeException("输入的折扣类型错误!");
442         }
443     }
444 }
445 
446 class Order {
447     int orderNum;//序号
448     String customerName;//用户名
449     String customerPhone;//手机号码
450     String day;
451     String time;
452     int sum;
453     int sumDiscount;
454     Menu menu;//菜单
455     ArrayList<Record> records = new ArrayList<>();//保存订单上每一道的记录
456 
457     public Order() {}
458 
459     public Order(int orderNum, String customerName, String customerPhone, String day, String time) {
460         this.orderNum = orderNum;
461         this.customerName = customerName;
462         this.customerPhone = customerPhone;
463         this.day = day;
464         this.time = time;
465     }
466 
467     public void setMenu(Menu menu) {
468         this.menu = menu;
469     }
470 
471     //添加一条菜品信息到订单中。
472     boolean addRecord(int recordNum, String dishName, Integer spicy, int portion, int num, Replace replace) {
473         if (menu != null) {
474             Dish dish = menu.searthDish(dishName);
475             if (dish != null) {
476                 if ("川菜".equals(dish.getType()) && (spicy < 0 || spicy > 5)) {
477                     System.out.println("spicy num out of range :" + spicy);
478                     return false;
479                 }
480                 if ("晋菜".equals(dish.getType()) && (spicy < 0 || spicy > 4)) {
481                     System.out.println("acidity num out of range :" + spicy);
482                     return false;
483                 }
484                 if ("浙菜".equals(dish.getType()) && (spicy < 0 || spicy > 3)) {
485                     System.out.println("sweetness num out of range :" + spicy);
486                     return false;
487                 }
488                 //遍历记录,避免添加重复的记录
489                 for (Record record : records) {
490                     if (record.getDish().getName().equals(dishName)
491                             && record.getSpicy() == spicy
492                             && record.getPortion() == portion
493                             && record.getReplace() == replace) {
494                         return true;
495                     }
496                 }
497                 records.add(new Record(recordNum, dish, spicy, portion, num, replace));
498                 return true;
499             } else {
500                 System.out.println(dishName + " does not exist");
501                 return false;
502             }
503         } else {
504             return false;
505         }
506     }
507 
508     public boolean deleteRecord(int recordNum) {
509         Iterator<Record> iterator = records.iterator();
510         while (iterator.hasNext()) {
511             Record record = iterator.next();
512             if (record.getRecordNum() == recordNum) {
513                 iterator.remove();
514                 return true;
515             }
516         }
517         System.out.println("Error: Record not found");
518         return false;
519     }
520 }
521 
522 class Replace {
523     private final int originNum;
524     private final int replaceNum;
525 
526     public Replace(int originNum, int replaceNum) {
527         this.originNum = originNum;
528         this.replaceNum = replaceNum;
529     }
530 
531     public int getOriginNum() {
532         return originNum;
533     }
534 
535     public int getReplaceNum() {
536         return replaceNum;
537     }
538 }

Menu

它包含一个 ArrayList 类型的成员变量 dishs,用于保存所有菜品信息。

Menu 类中定义了三个方法:searthDishupdateDish 和 addDish

searthDish 方法接受一个菜品名称作为参数,它遍历 dishs 数组,查找是否有与输入菜品名称相同的菜品。如果找到,则返回该菜品对象;否则返回 null。如果输入的菜品名称为 null,则抛出异常。

updateDish 方法接受四个参数:菜品名称、类型、单价和特殊标记。它遍历 dishs 数组,查找是否有与输入菜品名称相同的菜品。如果找到,则更新该菜品的信息,并返回 true;否则返回 false

addDish 方法接受四个参数:菜品名称、类型、单价和特殊标记。它根据这些参数创建一个新的 Dish 对象,并将其添加到 dishs 数组中。最后,它返回新创建的 Dish 对象。

Dish

它有四个实例变量:nametypeunitPrice 和 isVegetarian。构造函数接受四个参数来初始化这些实例变量。这个类中还有五个方法:getName()getType()getUnitPrice()isVegetarian() 和 getPrice(int portion)。前四个方法是简单的 getter,返回相应实例变量的值。最后一个方法,getPrice(int portion),接受一个表示分量大小的整数参数,并根据分量大小返回菜品的价格。价格使用 switch 语句计算。如果分量大小为 1,则价格等于单价。如果分量大小为 2,则价格为单价的 1.5 倍。如果分量大小为 3,则价格是单价的两倍。如果分量大小不是 1、2 或 3,则抛出异常。

Replace

它包含两个私有的 final 类型的成员变量:originNum 和 replaceNum,分别表示原始数字和替换数字。

Replace 类中定义了一个构造方法,它接受两个参数:原始数字和替换数字。它将这两个参数分别赋值给 originNum 和 replaceNum 成员变量。

此外,Replace 类还定义了两个公有的访问器方法:getOriginNum 和 getReplaceNum。它们分别返回 originNum 和 replaceNum 成员变量的值。

这段代码定义了一个简单的类,用于表示替换操作。它包含原始数字和替换数字两个成员变量,并提供了访问这些成员变量的方法。

Record 

它有六个实例变量:recordNumdishspicyportionnum 和 replace。构造函数接受六个参数来初始化这些实例变量。这个类中还有八个方法:getRecordNum()getDish()getSpicy()getPortion()getNum()getReplace()getPrice() 和 getDiscountPrice(int discountType)。前六个方法是简单的 getter,返回相应实例变量的值。第七个方法,getPrice(),返回菜品的总价格,即菜品单价乘以数量。第八个方法,getDiscountPrice(int discountType),接受一个表示折扣类型的整数参数,并根据折扣类型返回菜品的折扣价格。价格使用 switch 语句计算。如果折扣类型为 1 或 2,则价格为菜品单价乘以数量再乘以相应的折扣系数。如果折扣类型为 3,则价格为菜品单价乘以数量。如果折扣类型不是 1、2 或 3,则抛出异常。

Order 

它有九个实例变量:orderNumcustomerNamecustomerPhonedaytimesumsumDiscountmenu 和 records。构造函数接受五个参数来初始化前五个实例变量。这个类中还有四个方法:无参构造函数、带参构造函数、setMenu(Menu menu) 和 addRecord(int recordNum, String dishName, Integer spicy, int portion, int num, Replace replace)

无参构造函数不做任何操作。带参构造函数接受五个参数来初始化前五个实例变量。第三个方法,setMenu(Menu menu),接受一个 Menu 类型的参数并将其赋值给实例变量 menu。第四个方法,addRecord(int recordNum, String dishName, Integer spicy, int portion, int num, Replace replace),接受六个参数并尝试将一条菜品信息添加到订单中。首先检查实例变量 menu 是否为 null,如果不为 null,则调用 menu.searthDish(dishName) 方法查找菜品。如果找到了菜品,则根据菜品类型检查辣度是否在合理范围内,如果不在合理范围内,则打印错误信息并返回 false。然后遍历记录,避免添加重复的记录。最后将新建的 Record 对象添加到 records 列表中并返回 true。

两个静态方法

dateToWeek 方法接受一个日期字符串作为参数,格式为 “yyyy/MM/dd”。它使用 SimpleDateFormat 类将日期字符串解析为日期对象,并使用 Calendar 类获取该日期是星期几。最后,它返回一个整数,表示该日期是星期几(0 表示星期天,1 表示星期一,依此类推)。

isAvailable 方法接受两个参数:一个整数 weekDays 和一个时间字符串 timeNow。它使用 SimpleDateFormat 类将时间字符串解析为时间对象,并获取其毫秒值。然后,它定义了一些时间范围,并根据输入的星期几和时间判断当前时间是否在这些时间范围内。如果在,则返回相应的整数值(1、2 或 3),否则返回 0。

UML

 期中考试

题目1

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner scanner = new Scanner(System.in);
 6         double radius = scanner.nextDouble();
 7         if (radius <= 0) {
 8             System.out.println("Wrong Format");
 9         } else {
10             Circle circle = new Circle(radius);
11             System.out.println(String.format("%.2f", circle.getArea()));
12         }
13     }
14 }
15 
16 class Circle {
17     private double radius;
18 
19     public Circle(double radius) {
20         this.radius = radius;
21     }
22 
23     public double getArea() {
24         return Math.PI * radius * radius;
25     }
26 }

在这段代码中,我们首先从控制台读取圆的半径。如果半径小于等于 0,则输出 “Wrong Format”。否则,我们创建一个 Circle 对象,并使用它的 getArea 方法计算圆的面积。最后,我们使用 String.format 方法格式化输出结果,保留两位小数。总的来说这道题目很简单,同时它也涉及道后面的几道题目,所以这题务必用面对对象的方法来写。

题目2

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner scanner = new Scanner(System.in);
 6         double x1 = scanner.nextDouble();
 7         double y1 = scanner.nextDouble();
 8         double x2 = scanner.nextDouble();
 9         double y2 = scanner.nextDouble();
10         Point point1 = new Point(x1, y1);
11         Point point2 = new Point(x2, y2);
12         Rectangle rectangle = new Rectangle(point1, point2);
13         System.out.println(String.format("%.2f", rectangle.getArea()));
14     }
15 }
16 
17 class Point {
18     private double x;
19     private double y;
20 
21     public Point(double x, double y) {
22         this.x = x;
23         this.y = y;
24     }
25 
26     public double getX() {
27         return x;
28     }
29 
30     public double getY() {
31         return y;
32     }
33 }
34 
35 class Rectangle {
36     private Point point1;
37     private Point point2;
38 
39     public Rectangle(Point point1, Point point2) {
40         this.point1 = point1;
41         this.point2 = point2;
42     }
43 
44     public double getArea() {
45         return Math.abs((point1.getX() - point2.getX()) * (point1.getY() - point2.getY()));
46     }
47 }

在这段代码中,我们首先从控制台读取两个坐标点的坐标值。然后,我们创建两个 Point 对象,并使用它们创建一个 Rectangle 对象。接着,我们使用 Rectangle 对象的 getArea 方法计算矩形的面积。最后,我们使用 String.format 方法格式化输出结果,保留两位小数。同样很简单,但是也是后面题目的前前提。

题目3

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner input = new Scanner(System.in);
 6         int choice = input.nextInt();
 7         switch (choice) {
 8             case 1:
 9                 double radius = input.nextDouble();
10                 Shape circle = new Circle(radius);
11                 printArea(circle);
12                 break;
13             case 2:
14                 double x1 = input.nextDouble();
15                 double y1 = input.nextDouble();
16                 double x2 = input.nextDouble();
17                 double y2 = input.nextDouble();
18                 Point leftTopPoint = new Point(x1, y1);
19                 Point lowerRightPoint = new Point(x2, y2);
20                 Rectangle rectangle = new Rectangle(leftTopPoint, lowerRightPoint);
21                 printArea(rectangle);
22                 break;
23         }
24     }
25 
26     public static void printArea(Shape shape) {
27         System.out.println(String.format("%.2f", shape.getArea()));
28     }
29 }
30 
31 abstract class Shape {
32     public abstract double getArea();
33 }
34 
35 class Circle extends Shape {
36     private double radius;
37 
38     public Circle(double radius) {
39         this.radius = radius;
40     }
41 
42     @Override
43     public double getArea() {
44         return Math.PI * radius * radius;
45     }
46 }
47 
48 class Point {
49     private double x;
50     private double y;
51 
52     public Point(double x, double y) {
53         this.x = x;
54         this.y = y;
55     }
56 
57     public double getX() {
58         return x;
59     }
60 
61     public double getY() {
62         return y;
63     }
64 }
65 
66 class Rectangle extends Shape {
67     private Point point1;
68     private Point point2;
69 
70     public Rectangle(Point point1, Point point2) {
71         this.point1 = point1;
72         this.point2 = point2;
73     }
74 
75     @Override
76     public double getArea() {
77         return Math.abs((point1.getX() - point2.getX()) * (point1.getY() - point2.getY()));
78     }
79 }
}

在这段代码中,我们首先从控制台读取类型选择和图形参数。然后,根据选择的类型创建相应的图形对象(Circle 或 Rectangle)。接着,我们使用 printArea 方法计算并输出图形的面积。

此外,我们还定义了一个抽象类 Shape,它包含一个抽象方法 getAreaCircle 和 Rectangle 类都继承自 Shape 类,并分别实现了 getArea 方法。难度不大。

习题四

 1 import java.util.ArrayList;
 2 import java.util.Comparator;
 3 import java.util.Scanner;
 4 
 5 public class Main {
 6     public static void main(String[] args) {
 7         Scanner input = new Scanner(System.in);
 8         ArrayList<Shape> list = new ArrayList<>();
 9 
10         int choice = input.nextInt();
11 
12         while (choice != 0) {
13             switch (choice) {
14                 case 1:
15                     double radius = input.nextDouble();
16                     Shape circle = new Circle(radius);
17                     list.add(circle);
18                     break;
19                 case 2:
20                     double x1 = input.nextDouble();
21                     double y1 = input.nextDouble();
22                     double x2 = input.nextDouble();
23                     double y2 = input.nextDouble();
24                     Point leftTopPoint = new Point(x1, y1);
25                     Point lowerRightPoint = new Point(x2, y2);
26                     Rectangle rectangle = new Rectangle(leftTopPoint, lowerRightPoint);
27                     list.add(rectangle);
28                     break;
29             }
30             choice = input.nextInt();
31         }
32 
33         list.sort(Comparator.naturalOrder());
34 
35         for (int i = 0; i < list.size(); i++) {
36             System.out.print(String.format("%.2f", list.get(i).getArea()) + " ");
37         }
38     }
39 }
40 
41 abstract class Shape implements Comparable<Shape> {
42     public abstract double getArea();
43 
44     @Override
45     public int compareTo(Shape o) {
46         return Double.compare(this.getArea(), o.getArea());
47     }
48 }
49 
50 class Circle extends Shape {
51     private double radius;
52 
53     public Circle(double radius) {
54         this.radius = radius;
55     }
56 
57     @Override
58     public double getArea() {
59         return Math.PI * radius * radius;
60     }
61 }
62 
63 class Point {
64     private double x;
65     private double y;
66 
67     public Point(double x, double y) {
68         this.x = x;
69         this.y = y;
70     }
71 
72     public double getX() {
73         return x;
74     }
75 
76     public double getY() {
77         return y;
78     }
79 }
80 
81 class Rectangle extends Shape {
82     private Point point1;
83     private Point point2;
84 
85     public Rectangle(Point point1, Point point2) {
86         this.point1 = point1;
87         this.point2 = point2;
88     }
89 
90     @Override
91     public double getArea() {
92         return Math.abs((point1.getX() - point2.getX()) * (point1.getY() - point2.getY()));
93     }
94 }

对于习题四,只需要加上Comparable接口即可,并且要注意compareTo方法返回的值以实现按照图形的面积大小进行排序。

踩坑心得

  1. 注意处理超出范围的返回值错误,避免返回不正确的数据或者返回无效的日期。
  2. 在使用Java语言时,要注意大小写。Java对于输入的语法要求非常严格,很多报错是因为方法名称没有正确的大写首字母。
  3. 当点菜记录中存在相同菜名和份额的情况时,应该将它们合并成一条记录进行计算,以避免四舍五入误差带来的问题。
  4. 注意检查价格算法,特别是特色菜的定价算法和打折时间。确保算法正确并准确反映实际情况。
  5. 在调用方法类函数时,请确保在方法名后加上括号()来进行调用,以避免报错。

改进建议

 

在设计类时,需要深入思考每个类的作用、责任和关联,确保类的设计合理,并且能够满足系统的需求。每个类应该明确定义其包含的属性和方法,以及不同类之间的关系。

 

属性:确定每个类所需的属性,这些属性代表类的特征和状态。例如,餐厅类可能包括名称、地址、联系方式等属性;菜品类可能包括名称、价格、描述等属性。

 

方法:确定每个类应该具备的方法,这些方法用于执行相应的操作。例如,在餐厅类中可能包括预订、点菜、结账等方法;在菜品类中可能包括展示菜品、计算总价等方法。

 

类之间的关系:考虑不同类之间的关系,例如继承、关联或依赖关系等。例如,可以创建一个订单类,它关联了餐厅类和菜品类,表示顾客在某个餐厅点的菜品。

 

同时,在程序的编写中,还是要多运用list之类的数据存储方式,数组之类的方式太过于麻烦。注意遵循面向对象设计原则,如单一职责原则、开闭原则等,以提高代码的可维护性和灵活性。

 

在使用继承的方法时,可能还不够熟练导致出现一些错误。同样,在传递参数的方法方面也缺乏一些熟练度,容易出现错误。为了避免未来出现错误,建议多加练习和使用这些特性,以增加对它们的熟悉程度。只有通过实践和经验积累,才能更好地掌握和运用这些技巧。

总结

通过这三次题目集。我更加熟悉了类的声明、创建与使用方法、类的构造方法的定义与使用方法、引用变量与对象实例之间的关系与区别以及方法重载的实现方式等等用法。我填补了在上课时没有完全理解或者没有听懂的知识点,比如容器类在期中考试的第三题中涉及到的内容。然而,在构造一个对象数组的构造上,我还有一些困惑。另外,我还没有详细了解抽象父类中方法是否需要用抽象方法或空方法体的差别,但我打算花时间进一步了解这方面的知识。通过这些练习,我更好地掌握了所学知识。

 

标签:strs,int,orders,Blog,record,&&,public
From: https://www.cnblogs.com/Zankjavablog/p/17512944.html

相关文章

  • oo第二次BLOG
    一:总结  pta4,5和期中的作业其实主要用于对所学知识的练习,第六次作业只有一到成绩题目有一定的难度,后两次作业的题目这相对简单一些。作业尽力去完成,虽然有些不完美,但已经尽了全力。七,八次作业折相对简单一些,完成情况也相对好一点。二:作业实现7-1菜单计价程序-4......
  • 菜单4、5以及期中考试总结-BLOG-PTA-4、5
    22201612-刘健涛目录(1)前言(2)设计与分析(3)踩坑心得(4)改进建议(5)总结正文(1)前言  (2)设计与分析(3)踩坑心得(4)改进建议(5)总结......
  • BLOG-2
    一、题目集分析本次博客将对PTA的第四,五次题目集和期中考试的题目进行分析,情况如下:(1)题量分析:第四次练习共计1题期中考试共计4题第五次练习共计1题从题量而言,数量适中。(2)知识点分析:第四次题目集继续为菜单的续集,对菜单的难度进行增加,主要体现在对异常信息的处......
  • BLOG_OOP_期中考试
    前言涉及知识点1.对于创建对象和类的初步实践;如构建圆类和矩形类;1.对于抽象类和继承与多态的认识;如构建shape类;题量不多,可以完成。难度不大,可以完成。设计与分析题目源码如下importjava.util.*;publicclassMain{publicstaticvoidmain(String[]......
  • blog2
    第四次题目集7-1菜单计价程序-4分数100作者蔡轲单位南昌航空大学本体大部分内容与菜单计价程序-3相同,增加的部分用加粗文字进行了标注。设计点菜计价程序,根据输入的信息,计算并输出总价格。输入内容按先后顺序包括两部分:菜单、订单,最后以"end"结束。菜单由一条或多条菜品记......
  • pta题目集4~5及期中考试总结性blog
    一、前言总结三次题目集的知识点、题量、难度等情况第四次题目集主要更新了各种异常情况,是对代码正确度的深入考察,涉及时间的格式问题,信息的格式问题各种格式问题等等,涉及到hashset、面向对象编程的封装性、BigDecimal类关于精确小数的运算以及了解Scanner类中nextLine()等方法......
  • 面向对象程序编程PTA题目集4、5以及期中考试的总结性Blog
    1.对之前发布的PTA题目集4、5以及期中考试的总结性Blog,内容要求如下:(1)前言:总结之前所涉及到的知识点、题量、难度等情况期中考试作业:知识点:主要就是考了对类的使用,和不同类间的相互配合使用,还有对于一个程序的不断循环使用(相比之前更加灵活,可以自定义输入的个数),正则表达(可用可不......
  • BLOG-2
    前言:本篇blog主要分析PTA4和PTA5的两道菜单计价程序和期中考试题目。实现菜单计价程序是一个常见的编程练习,可以帮助学习者巩固Java语言的基础知识和面向对象编程的概念。下面将介绍涉及的知识点和难度。1.知识点:-类和对象:程序需要设计菜单类和菜品类,通过创建对象来表示不......
  • java第二次blog
    1.前言:4~6次pta题目集难度上升,代码量增加,考察了对类的设计以及如何实现类间关系等。难度较大。涉及到了去重排序循环遍历等。还有API接口,JAVA自带的实现类,包装类,成员方法等,涉及的知识面更广更难。 2.设计分析: 7-1菜单计价程序-3:设计点菜计价程序,根据输入的信息,计算......
  • 题目集6-8的总结性Blog
    一、前言第6-8次的pta没有延续之前的菜单计价程序,主要是围绕课程成绩统计程序进行的。第六次大作业就是成绩统计程序,第七次大作业则增加了对HashMap和多态的一个考察,第八次大作业则是增加了对Arraylist部分知识点的考察。这三次作业不再是菜单的设计,而是改为学生成绩的统计,但还是......