PTA题目集4-5和期中
总结
涉及的知识点有:
- 类的创建:代码定义了一个名为Circle的类,用于表示圆形对象。
- 封装和私有属性:代码使用了private关键字来声明私有属性radius,这样它只能被类内部的方法访问。
- 构造方法:代码定义了一个构造方法Circle(double radius),用于创建Circle对象并初始化radius属性。
- 成员方法:代码定义了一个成员方法calculateArea(),用于计算圆的面积。
- 输入和输出:代码使用Scanner对象从控制台读取用户输入的半径,使用System.out.println()方法输出结果。
- 条件判断:代码使用if语句进行条件判断,检查输入的半径是否合法。
- 格式化输出:代码使用String.format()方法控制输出结果的小数精度。
- ArrayList容器的使用:使用ArrayList作为存储图形对象的容器。
- 接口Comparable的实现:Shape类实现了Comparable接口,并重写了compareTo()方法来定义排序规则。
- 使用Comparator接口:在排序方法中使用Comparator.naturalOrder()方法来实现默认的升序排序。
split(String regex): 这个方法用于按照指定的分隔符将字符串拆分成字符串数组。在代码中,使用split(" ")来将str字符串按空格进行拆分,并将拆分后的结果存储在字符串数组b中。parseInt(String s): 这个方法用于将字符串转换为整数。在代码中,使用parseInt(c[2])和parseInt(str1)来将字符串转换为整数。round(double a): 这个方法用于将小数四舍五入为最接近的整数。在代码中,使用Math.round(1.0 * taste[i][j] / taste[i][j + 3])来对计算结果进行四舍五入。
设计与分析
题目集四
-
Dish类用于表示菜品,它应该包含菜品名称和基础价格两个属性。你可以在Dish类中定义一个计算菜品价格的方法,根据传入的份额参数(输入数据只能是1/2/3,分别代表小/中/大份)计算菜品的价格。
-
Menu类用于表示菜谱,包含饭店提供的所有菜品信息。你可以在Menu类中定义一个菜品数组,用于保存所有菜品信息。此外,你还需要在Menu类中实现一些方法,比如根据菜名在菜谱中查找菜品信息、添加一道菜品信息等。
-
Record类用于表示点菜记录,保存订单上的一道菜品信息。它应该包含序号、菜品、份额等属性。你可以在Record类中定义一个计算价格的方法,用于计算本条记录的价格。
-
Order类用于表示订单,保存用户点的所有菜的信息。它应该包含记录数组,用于保存订单上的每一道菜品记录。在Order类中,你可以定义一些方法,比如计算订单的总价、添加一条菜品记录、根据序号删除一条记录等。
菜单输入时增加特色菜,特色菜的输入格式:菜品名+英文空格+基础价格+"T"
例如:麻婆豆腐 9 T
菜价的计算方法:
周一至周五 7折, 周末全价。
注意:不同的四舍五入顺序可能会造成误差,请按以下步骤累计一桌菜的菜价:
计算每条记录的菜价:将每份菜的单价按份额进行四舍五入运算后,乘以份数计算多份的价格,然后乘以折扣,再进行四舍五入,得到本条记录的最终支付价格。
最后将所有记录的菜价累加得到整桌菜的价格。
import java.text.ParseException; import java.time.DateTimeException; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.text.SimpleDateFormat; import java.util.Date; class Dish{ } class Menu{ } class order{ } public class Main { public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) throws ParseException { return nowTime.getTime() <= endTime.getTime() && nowTime.getTime() >= beginTime.getTime(); } public static boolean judge(int a,int b,int c){ if(b<1||b>12)return false; else if((a%4==0&&a%100!=0)||a%400==0){ if(b==2) return c >= 1 && c <= 29; } else { if(b==2)if(c<1||c>28)return false; if(b==1||b==3||b==5||b==8||b==7||b==10||b==12)if(c<1||c>31)return false; if(b==4||b==6||b==9||b==11) return c >= 1 && c <= 30; } return true; } public static boolean judgeMIN(int a,int b,int c,int d,int e,int f){ // 获取创建指定时间 try { LocalDateTime localDateTime = LocalDateTime.of(a,b,c,d,e,f); } catch (DateTimeException g) { return false; } return true; } public static boolean table(int []a,int b,int c){ for(int i=0;i<b;i++)if(a[i]==c)return true; return false; } public static boolean SearchNumber(String a){ String regExp="^[0-9]*[1-9][0-9]*$"; //得到一个模式对象 Pattern pattern = Pattern.compile(regExp); //创建匹配器 Matcher matcher = pattern.matcher(a); return matcher.matches(); } public static boolean SearchChinese(String a){ a = a.toLowerCase(); // 匹配的字符串的正则表达式 String regCharset = "[\\u4E00-\\u9FFF]+"; Pattern p = Pattern.compile(regCharset); Matcher matcher = p.matcher(a); return matcher.matches(); } public static boolean delete(int []a,int b,int c){ for(int i=0;i<b;i++)if(a[i]==c)return false; return true; } public static boolean special(String []nom,String dis,int nor){ for(int i=0;i<nor;i++){ if(nom[i].equals(dis))return false; } return true; } public static int week(int y, int m, int d) { int num; if (m == 1 || m == 2) { m += 12; y--; } int a = y / 100; int b = y % 100; num = (a / 4) - 2 * a + b + (b / 4) + (13 * (m + 1) / 5) + d - 1; return num % 7; } public static void main(String[] args) throws ParseException { SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy/MM/dd"); Date date1=simpleDateFormat.parse("2022/1/1"); Date date2=simpleDateFormat.parse("2023/12/31"); Date date3; int year=0, month = 0, day = 0, hh = 0, mm=0,ss=0; double ts = 0; Scanner input = new Scanner(System.in); String ds = ""; int wek = 0; int cn = 1; String[] put = new String[100]; String t,pr; String num = ""; String time; String h = ""; String str=""; String []str1=new String[5]; int nor=0; String [] normal=new String[100]; HashMap<String, Integer> menu = new HashMap<String, Integer>(); while (true) { int rt = 1; str=input.nextLine(); str1=str.split(" "); if(str1.length>=2&&str1.length<=3) { ds = str1[0]; pr = str1[1]; if(!SearchNumber(pr)||!SearchChinese(ds)) { System.out.println("wrong format"); continue; } normal[nor++]=ds; if (menu.containsKey(ds)) { menu.put(ds, Integer.parseInt(pr)); rt = 0; } else { menu.put(ds, Integer.parseInt(pr)); } } else if(str1.length<2){ ds = str1[0]; if(ds.equals("end")) { t="0"; break; } System.out.println("wrong format"); continue; } else if(str1.length>3){ ds=str1[0]; t="1"; break; } if(str1.length==3) { normal[--nor]=""; continue; } if (ds.equals("table") || ds.equals("1")) { t = "1"; break; } } for (Iterator<Map.Entry<String, Integer>> it = menu.entrySet().iterator(); ((Iterator<?>) it).hasNext(); ) { Map.Entry<String, Integer> item = it.next(); String key = item.getKey(); int value= item.getValue(); if(value>=300||value<=0) { System.out.println(key+" price out of range "+value); it.remove(); } } boolean wor=false; int []table=new int[50]; int tab=0; if(!ds.equals("table")){ cn--; ds=""; System.out.println("wrong format"); while(true){ t=input.next(); if(t.equals("table"))break; } } while (true) { int []delete=new int [150]; int order=0; int det=0; if (t.equals("table")) { ds=""; cn++; num = input.next(); if(!SearchNumber(num) || !(1 <= Integer.parseInt(num) && Integer.parseInt(num) <= 55)) { wor=true; System.out.println("wrong format"); while(true){ t=input.next(); if(t.equals("table")||t.equals("end"))break; } cn--; continue; } table[tab++]=Integer.parseInt(num); time = input.nextLine().replaceAll("[/]", " "); String[] Tim = time.split(" "); year = Integer.parseInt(Tim[1]); month = Integer.parseInt(Tim[2]); day = Integer.parseInt(Tim[3]); String date=year+"/"+month+"/"+day; date3=simpleDateFormat.parse(date); hh = Integer.parseInt(Tim[4]); mm = Integer.parseInt(Tim[5]); ss=Integer.parseInt(Tim[6]); wek = week(year, month, day); ts = hh * 1.0 + mm / 60.0; if (wek == 0) wek = 7; t = "1"; if (wek >= 1 && wek <= 5 && (ts < 10.5 || ts > 14.5 && ts < 17 || ts > 20.5)) { System.out.println ("table" + " " + num + " out of opening hours"); while(true){ t=input.next(); if(t.equals("table")||t.equals("end"))break; } cn--; continue; } if (wek == 7 && (ts < 9.5 || ts > 21)) { System.out.println("table" + " " + num + " out of opening hours"); while(true){ t=input.next(); if(t.equals("table")||t.equals("end"))break; } cn--; continue; } if(!belongCalendar(date3,date1,date2)){ System.out.println("not a valid time period"); cn--; while (true) { t = input.next(); if (t.equals("table") || t.equals("end")) break; } ds = ""; continue; } if (judgeMIN(year, month, day,hh,mm,ss) && Tim[1].length() == 4 && Tim[2].length() <= 2 && Tim[3].length() <= 2 && Tim[4].length() <= 2 && Tim[5].length() <= 2) System.out.println("table" + " " + num + ": "); else { System.out.println(num + " date error"); cn--; while (true) { t = input.next(); if (t.equals("table") || t.equals("end")) break; } ds = ""; continue; } } if (t.equals("end") || h.equals("end")) break; if (t.equals("0")) { System.out.println(); return; } int [] specialPrice=new int [100]; int spr=0; int cnt, sum = 0, max = 0; int[] recording = new int[100]; int re = 0, flag3 = 1, flag2 = 0; if (t.equals("1")) { if (ds.equals("table")) { wor = false; String[] Tim; num = str1[1]; if (!SearchNumber(num) || !(1 <= Integer.parseInt(num) && Integer.parseInt(num) <= 55)) { System.out.println("wrong format"); wor = true; while(true){ t=input.next(); if(t.equals("table")||t.equals("end"))break; } cn--; continue; } table[tab++] = Integer.parseInt(num); String ti=str1[2]+"/"+str1[3]; time = ti.replaceAll("[/]", " "); Tim = time.split(" "); year = Integer.parseInt(Tim[0]); month = Integer.parseInt(Tim[1]); day = Integer.parseInt(Tim[2]); String date=year+"/"+month+"/"+day; date3=simpleDateFormat.parse(date); hh = Integer.parseInt(Tim[3]); mm = Integer.parseInt(Tim[4]); ss=Integer.parseInt(Tim[5]); wek = week(year, month, day); ts = hh * 1.0 + mm / 60.0; if (wek == 0) wek = 7; if (wek >= 1 && wek <= 5 && (ts < 10.5 || ts > 14.5 && ts < 17 || ts > 20.5)) { System.out.println("table" + " " + num + " out of opening hours"); while (true) { t = input.next(); if (t.equals("table") || t.equals("end")) break; } cn--; continue; } if (wek == 7 && (ts < 9.5 || ts > 21)) { System.out.println("table" + " " + num + " out of opening hours"); while (true) { t = input.next(); if (t.equals("table") || t.equals("end")) break; } cn--; continue; } if(!belongCalendar(date3,date1,date2)){ System.out.println("not a valid time period"); cn--; while (true) { t = input.next(); if (t.equals("table") || t.equals("end")) break; } ds = ""; continue; } if (judgeMIN(year, month, day,hh,mm,ss) && Tim[0].length() == 4 && Tim[1].length() <= 2 && Tim[2].length() <= 2 && Tim[3].length() <= 2 && Tim[4].length() <= 2) System.out.println("table" + " " + num + ": "); else { System.out.println(num + " date error"); cn--; while (true) { t = input.next(); if (t.equals("table") || t.equals("end")) break; } ds = ""; continue; } } while (!t.equals("end")) { if (flag3 == 1 ) t = input.next(); if (t.equals("end") || t.equals("table")) break; if(t.length()>2) { System.out.println("invalid dish"); continue; } if(!SearchNumber(t)||t.charAt(0)=='0') { System.out.println("wrong format"); continue; } cnt = 0; int flag = 0; String dish = input.next(); if (dish.equals("delete")) { if (flag2 == 1 && flag3 == 0) t = h; int p = Integer.parseInt(t); if(!delete(delete,det,p)){ System.out.println("deduplication "+p); h = input.next(); flag3 = 0; if (h.equals("end")) break; flag2 = 1; t = h; continue; } delete[det++]=p; if (p < 1 || p > max || recording[p - 1] == 0) System.out.println("delete error;"); if (p >= 1 && p <= max && recording[p - 1] != 0) { sum -= recording[p - 1]; if(sum<0) { sum = 0; specialPrice[spr++] = -recording[p - 1]; } recording[p - 1] = 0; } h = input.next(); flag3 = 0; if (h.equals("end")) break; flag2 = 1; t = h; continue; } else flag3 = 1; String size1 = input.next(); if (size1.length()!=1) { String a; int b; a = input.next(); b = input.nextInt(); if(!table(table,tab,Integer.parseInt(t))){ System.out.println("Table number :"+t+" does not exist"); continue; } if (menu.containsKey(size1)) { int price = menu.get(size1); switch (a) { case "1": cnt += price; break; case "2": if (price % 2 == 1) cnt += price / 2 + price + 1; else cnt += price / 2 + price; break; case "3": cnt += 2 * price; break; } cnt*=b; sum += cnt; System.out.println(dish + " table" + " " + num + " pay for " + "table" + " " + t + " " + cnt); } else {System.out.println(dish + " does not exist"); } continue; } int b = input.nextInt(); boolean errors=false; if (!menu.containsKey(dish)){ errors=true; cnt=0; recording[re++] = 0; System.out.println(dish + " does not exist"); max++; }else { flag = 1; int price = menu.get(dish); switch (size1) { case "1": cnt += price; break; case "2": if (price % 2 == 1) cnt += price / 2 + price + 1; else cnt += price / 2 + price; break; case "3": cnt += 2 * price; break; default: System.out.println(t + " portion out of range " + size1); continue; } } if(b>15&&!errors){ recording[re++] = 0; max++; System.out.println(t+" num out of range "+b); continue; } int ord=Integer.parseInt(t); if(ord<=order){ System.out.println("record serial number sequence error"); while (true) { t = input.next(); if (t.equals("table") || t.equals("end")) { } else {flag3=0; } break; } ds = ""; continue; }else if(!errors)order=ord; if (flag == 1) { if(special(normal,dish,nor)&&1<=wek&&wek<=5){ specialPrice[spr++]=cnt*b; cnt*=b; max++; System.out.println(t + " " + dish + " " + cnt); recording[re++] = cnt; cnt= (int) Math.round(cnt*0.7); continue; } cnt *= b; sum += cnt; recording[re++] = cnt; System.out.println(t + " " + dish + " " + cnt); max++; } } int s=0; int initialPrice=0; for(int k=0;k<spr;k++)s+=specialPrice[k]; initialPrice=s+sum; s=(int)Math.round(s*0.7); if ((wek == 7 || wek == 6) && !t.equals("0") && (ts >= 9.5) && (ts <= 21)) put[cn - 1] = ("table" + " " + num + ": " + initialPrice+" "+ (sum+s)); if ((wek >= 1 && wek <= 5) && !t.equals("0") && (ts >= 17) && (ts <= 20.5)) put[cn - 1] = ("table" + " " + num + ": " + initialPrice+" "+((Math.round(sum * 0.8)+s))); if ((wek >= 1 && wek <= 5) && !t.equals("0") && (ts >= 10.5) && (ts <= 14.5)) put[cn - 1] = ("table" + " " + num + ": " + initialPrice+" "+(Math.round(sum * 0.6)+s)); } } if(!wor) for (int j = 0; j < cn; j++) System.out.println(put[j]); } }
题目集五
菜单输入时增加特色菜,特色菜的输入格式:菜品名+英文空格+口味类型+英文空格+基础价格+"T"
例如:麻婆豆腐 川菜 9 T
菜价的计算方法:
周一至周五 7折, 周末全价。
特色菜的口味类型:川菜、晋菜、浙菜
川菜增加辣度值:辣度0-5级;对应辣度水平为:不辣、微辣、稍辣、辣、很辣、爆辣;
晋菜增加酸度值,酸度0-4级;对应酸度水平为:不酸、微酸、稍酸、酸、很酸;
浙菜增加甜度值,甜度0-3级;对应酸度水平为:不甜、微甜、稍甜、甜;
例如:麻婆豆腐 川菜 9 T
输入订单记录时如果是特色菜,添加口味度(辣/酸/甜度)值,格式为:序号+英文空格+菜名+英文空格+口味度值+英文空格+份额+英文空格+份数
- 创建菜单对象和客户列表对象。
- 根据输入内容,逐行读取并解析信息,并根据桌号标识来判断创建新的桌菜对象或代点菜对象。
- 根据解析的内容,分别在菜单对象和订单对象中添加相应的记录。
- 根据桌号找到对应的客户,将桌菜对象添加到客户的桌菜列表中。
- 遍历客户列表,计算每桌的总价和折扣后总价。
- 输出每桌的信息。
- 根据姓名字母顺序排序客户列表,并输出每位客户需要支付的金额。
import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.DateTimeException; import java.time.LocalDateTime; import java.util.*; import static java.lang.Integer.parseInt; public class Main { public static boolean isNumeric(String string) { //判断是否为数字 try { parseInt(string); return true; } catch (NumberFormatException e) { return false; } } Scanner input = new Scanner(System.in); int year1, year2, year3; int month1, month2, month3; int day1, day2, day3; String data1 = input.nextLine(); String data2 = input.next(); String data3 = input.next(); public static boolean searchCall(String threeCall) { String[] CallNumber = new String[]{"180", "181", "189", "133", "135", "136"}; int i = 0; while (i < CallNumber.length) { if (!CallNumber[i].equals(threeCall)) { i++; } else { return false; } } return true; } abstract class Person { } abstract class Plant { } abstract class AbstractTransport { } abstract class Boat extends AbstractTransport { } public static void main(String[] args) throws ParseException { new SimpleDateFormat("yyyy/MM/dd HH/mm/ss"); Menu menu = new Menu(); HashMap<String, String> hash = new HashMap<>(); String[] customer = new String[30]; int cnt = 0; ArrayList<Table> tables = new ArrayList<>(); Scanner input = new Scanner(System.in); String[] zheCai = new String[]{"不甜", "微甜", "稍甜", "甜"}; String[] jinCai = new String[]{"不酸", "微酸", "稍酸", "酸", "很酸"}; String[] chuanCai = new String[]{"不辣", "微辣", "稍辣", "辣", "很辣", "爆辣"}; int[] tastedGrade = new int[100]; int[] tastedNumber = new int[100]; String str1; String str2; String str3 = ""; int[][] taste = new int[20][7]; int table_count = 0; int i; int portion = 0, number = 0; //份额,份数 while (true) {// 输入菜单 str1 = input.next(); if (Objects.equals(str1, "T")) { // 判断上一道菜是否为特价菜 if (Objects.equals(str3, " ")) { menu.dishes.remove(menu.dishes.size() - 1); System.out.println("wrong format"); continue; } menu.dishes.get(menu.dishes.size() - 1).isT = true; str1 = input.next(); } if (Objects.equals(str1, "table")) break; // 结束菜谱输入 if (Objects.equals(str1, "end")) break; // 仅有菜谱的情况 str2 = input.next(); str3 = " "; if (!isNumeric(str2)) { str3 = str2; str2 = input.next(); } menu.dishes.add(menu.addDish(str1, parseInt(str2), str3)); } if (str1.equals("end")) return; while (!str1.equals("end")) { int chuanGrade = 0; int chuanNumber = 0; int zheGrade = 0; int zheNumber = 0; int jinGrade = 0; int jinNumber = 0; String[] a; String ord; String call; String useName; Table tab = new Table(); ord = input.nextLine(); a = ord.split(" "); str2 = a[1]; useName = a[3]; call = a[4]; String threeCall = call.substring(0, 3); if (useName.length() > 10 || call.length() != 11 || searchCall(threeCall)) { System.out.println("wrong format"); break; } String[] Date = a[5].split("/"); String[] Time = a[6].split("/"); tab.num = parseInt(str2); int[] intDate = new int[3]; int[] intTime = new int[3]; for (i = 0; i < 3; i++) { intDate[i] = parseInt(Date[i]); intTime[i] = parseInt(Time[i]); } try { tab.time = LocalDateTime.of(intDate[0], intDate[1], intDate[2], intTime[0], intTime[1], intTime[2]); //时间判断 tables.add(tab); if (!tab.isOpen()) { System.out.println("table " + str2 + " out of opening hours"); do { str1 = input.next(); } while (!Objects.equals(str1, "end") && !Objects.equals(str1, "table")); continue; } } catch (DateTimeException e) { System.out.println(tab.num + " date error"); break; } System.out.println("table " + str2 + ": "); while (true) { str1 = input.next(); if (Objects.equals(str1, "end")) break; if (Objects.equals(str1, "table")) break; str2 = input.next(); // 判断是否为代点 if (isNumeric(str2)) { //判断代点桌号是否存在 boolean exist = false; int j = 0; while (j < tables.size()) { if (tables.get(j).num == parseInt(str1)) { exist = true; break; } j++; } //若存在则完成代点 if (exist) { System.out.print(parseInt(str2) + " table " + tables.get(table_count).num + " pay for table " + parseInt(str1) + " "); String str = str1; Record treat = new Record(); str1 = input.next(); treat.ds = menu.dishes.get(menu.searchDish(str1)); if (menu.dishes.get(menu.searchDish(str1)).isT) { str3 = input.next(); tastedGrade[parseInt(str1)] = parseInt(str3); } else str3 = " "; portion = input.nextInt(); number = input.nextInt(); tastedNumber[parseInt(str1)] = number; treat.portion = portion; treat.number = number; System.out.print(treat.getPrice() + "\n"); if (menu.dishes.get(menu.searchDish(str1)).taste.equals("晋菜")) { if (parseInt(str3) < 0 || parseInt(str3) > 4) { System.out.println("acidity num out of range :" + jinGrade); continue; } taste[parseInt(str) - 1][1] += parseInt(str3) * number; taste[parseInt(str) - 1][4] += number; } if (menu.dishes.get(menu.searchDish(str1)).taste.equals("川菜")) { if (parseInt(str3) < 0 || parseInt(str3) > 5) { System.out.println("spicy num out of range :" + str3); continue; } taste[parseInt(str) - 1][0] += parseInt(str3) * number; taste[parseInt(str) - 1][3] += number; } if (menu.dishes.get(menu.searchDish(str1)).taste.equals("浙菜")) { if (parseInt(str3) < 0 || parseInt(str3) > 3) { System.out.println("sweetness num out of range :" + str3); continue; } taste[parseInt(str) - 1][2] += parseInt(str3) * number; taste[parseInt(str) - 1][5] += number; } tables.get(table_count).add(menu, "代点", str2, str1, portion, number); } //若不存在则输出内容 else { System.out.println("Table number :" + parseInt(str1) + " does not exist"); } } // 若不是代点 else { // 若不为删除订单,则读入份数和大小 if (!str2.equals("delete")) { boolean t = false; if (menu.dishes.get(menu.searchDish(str2)).isT) { hash.put(str1, menu.dishes.get(menu.searchDish(str2)).taste); str3 = input.next(); portion = input.nextInt(); number = input.nextInt(); tastedGrade[parseInt(str1)] = parseInt(str3); tastedNumber[parseInt(str1)] = number; t = true; if (Objects.equals(menu.dishes.get(menu.searchDish(str2)).taste, "晋菜")) { if (parseInt(str3) < 0 || parseInt(str3) > 4) { System.out.println("acidity num out of range :" + str3); continue; } jinGrade += parseInt(str3) * number; jinNumber += number; } if (Objects.equals(menu.dishes.get(menu.searchDish(str2)).taste, "川菜")) { if (parseInt(str3) < 0 || parseInt(str3) > 5) { System.out.println("spicy num out of range :" + str3); continue; } chuanGrade += parseInt(str3) * number; chuanNumber += number; } if (Objects.equals(menu.dishes.get(menu.searchDish(str2)).taste, "浙菜")) { if (parseInt(str3) < 0 || parseInt(str3) > 3) { System.out.println("sweetness num out of range :" + str3); continue; } zheGrade += parseInt(str3) * number; zheNumber += number; } } else str3 = " "; if (!t) { portion = input.nextInt(); number = input.nextInt(); } } tables.get(table_count).add(menu, str3, str1, str2, portion, number); if (Objects.equals(str2, "delete")) { if ("晋菜".equals(hash.get(str1))) { jinGrade -= tastedGrade[parseInt(str1)]; jinNumber -= tastedNumber[parseInt(str1)]; } if ("川菜".equals(hash.get(str1))) { chuanGrade -= tastedGrade[parseInt(str1)]; chuanNumber -= tastedNumber[parseInt(str1)]; } if ("浙菜".equals(hash.get(str1))) { zheGrade -= tastedGrade[parseInt(str1)]; zheNumber -= tastedNumber[parseInt(str1)]; } hash.put(str1, ""); } } } taste[table_count][0] = chuanGrade; taste[table_count][1] = jinGrade; taste[table_count][2] = zheGrade; taste[table_count][3] = chuanNumber; taste[table_count][4] = jinNumber; taste[table_count][5] = zheNumber; // 本桌点菜结束,进入下一桌 tables.get(table_count).getSum(); int sum; String str = useName + " " + call + " " + tables.get(table_count).sum; String[] b; if (table_count == 0) customer[cnt++] = str; else { b = str.split(" "); boolean r = true; for (int l = 0; l < cnt; l++) { String[] c = customer[l].split(" "); if (b[0].equals(c[0])) { sum = parseInt(c[2]) + parseInt(b[2]); customer[l] = useName + " " + call + " " + sum; r = false; } } if (r) customer[cnt++] = str; } table_count++; } // 最终输出桌号订单信息 for (i = 0; i < table_count; i++) { if (tables.get(i).isOpen()) { System.out.print("table " + tables.get(i).num + ": " + tables.get(i).origSum + " " + tables.get(i).sum); for (int j = 0; j < 3; j++) { if (taste[i][j + 3] != 0) { if (j == 0) System.out.print(" 川菜 " + taste[i][j + 3] + " " + chuanCai[(int) Math.round(1.0 * taste[i][j] / taste[i][j + 3])]); if (j == 1) { System.out.print(" 晋菜 " + taste[i][j + 3] + " " + jinCai[(int) Math.round(1.0 * taste[i][j] / taste[i][j + 3])]); } if (j == 2) { System.out.print(" 浙菜 " + taste[i][j + 3] + " " + zheCai[(int) Math.round(1.0 * taste[i][j] / taste[i][j + 3])]); } } } System.out.println(); } else System.out.println("table " + tables.get(i).num + " out of opening hours"); } Arrays.sort(customer, 0, cnt); for (int j = 0; j < cnt; j++) { if (j < cnt - 1) System.out.println(customer[j]); else System.out.print(customer[j]); } } } class Dish { //菜单格式 String name; int price; String taste; boolean isT = false; } class Record { //点菜 int orderNum; //序号 Dish ds; //菜品 int portion; //份额 int number; //份数 boolean isDeleted = false; int getPrice() { if (portion == 2) return (int) Math.round(1.5 * ds.price) * number; else if (portion == 3) { return 2 * ds.price * number; } else return ds.price * number; } } class Menu { //菜单 ArrayList<Dish> dishes = new ArrayList<>(); int searchDish(String dishName) { for (int i = 0; i < dishes.size(); i++) { if (dishName.equals(dishes.get(i).name)) return i; } return -1; } Dish addDish(String dishName, int price, String taste) { Dish newDish = new Dish(); newDish.name = dishName; newDish.price = price; newDish.taste = taste; return newDish; } } class Order { //点菜 ArrayList<Record> records = new ArrayList<>(); Record addARecord(String tasteGrade, int orderNum, String dishName, int portion, int number, Menu menu) { Record newRecord = new Record(); newRecord.orderNum = orderNum; newRecord.ds = menu.dishes.get(menu.searchDish(dishName)); newRecord.portion = portion; newRecord.number = number; if (!Objects.equals(tasteGrade, "代点")) System.out.println(newRecord.orderNum + " " + newRecord.ds.name + " " + newRecord.getPrice()); return newRecord; } void delARecordByOrderNum(int orderNum) { int i, flag = 0; for (i = 0; i < records.size(); i++) { if (records.get(i).orderNum == orderNum) { if (!records.get(i).isDeleted) { records.get(i).isDeleted = true; } else { System.out.println("deduplication " + orderNum); } flag++; } } if (flag == 0) { System.out.println("delete error;"); } } } class Table { Order order = new Order(); int num; LocalDateTime time; long sum = 0; long origSum = 0; void add(Menu menu, String str3, String str1, String str2, int portion, int number) { if (str2.equals("delete")) { order.delARecordByOrderNum(parseInt(str1)); } else if (menu.searchDish(str2) == -1) { System.out.println(str2 + " does not exist"); } else { order.records.add(order.addARecord(str3, parseInt(str1), str2, portion, number, menu)); } } abstract class Animal { public Animal() { super(); } } void getSum() { double ts = time.getHour(); int wek = time.getDayOfWeek().getValue(); for (int i = 0; i < order.records.size(); i++) { if (!order.records.get(i).isDeleted) { origSum += order.records.get(i).getPrice(); if ((wek == 7 || wek == 6) && (ts >= 9.5) && (ts <= 21)) { sum += order.records.get(i).getPrice(); } else { if ((wek >= 1 && wek <= 5) && (ts >= 17) && (ts <= 20.5)) { if (!order.records.get(i).ds.isT) sum += Math.round(order.records.get(i).getPrice() * 0.8); else sum += Math.round(order.records.get(i).getPrice() * 0.7); } } if ((wek >= 1 && wek <= 5) && (ts >= 10.5) && (ts <= 14.5)) if (!order.records.get(i).ds.isT) { sum += Math.round(order.records.get(i).getPrice() * 0.6); } else sum += Math.round(order.records.get(i).getPrice() * 0.7); } } } public void add(int s, int location){ add(location,s); } boolean isOpen() { int weekday = time.getDayOfWeek().getValue(); if (weekday > 0 && weekday < 6) { if (time.getHour() >= 17 && time.getHour() < 20) return true; if (time.getHour() == 20) { if (time.getMinute() <= 30) return true; } else { if (time.getHour() > 10 && time.getHour() < 14) return true; } if (time.getHour() == 10) if (time.getMinute() >= 30) return true; if (time.getHour() == 14) return time.getMinute() <= 30; } else { if (time.getHour() > 9 && time.getHour() < 21) return true; if (time.getHour() == 9) if (time.getMinute() >= 30) return true; if (time.getHour() == 21) return time.getMinute() <= 30; } return false; } }
期中题目
测验1-圆类设计
创建一个圆形类(Circle),私有属性为圆的半径,从控制台输入圆的半径,输出圆的面积
import java.util.Scanner; public class Main { private double radius; // 私有属性:圆的半径 // 构造方法 public Main(double radius) { this.radius = radius; } // 计算圆的面积 public double calculateArea() { return Math.PI * radius * radius; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); if (scanner.hasNextDouble()) { double radius = scanner.nextDouble(); if (radius > 0) { Main circle = new Main(radius); double area = circle.calculateArea(); System.out.println( String.format("%.2f", area)); } else { System.out.println("Wrong Format"); } } else { System.out.println("Wrong Format"); } scanner.close(); } }
我们学到了如何用类和方法来组织代码,以及如何进行简单的输入输出操作。我们还学到了如何使用Math类中的数学函数来进行计算。
这题难度并不大,要注意一下输出的格式
测验2-类结构设计
设计一个矩形类,其属性由矩形左上角坐标点(x1,y1)及右下角坐标点(x2,y2)组成,其中,坐标点属性包括该坐标点的X轴及Y轴的坐标值(实型数),求得该矩形的面积。
import java.util.Scanner; public class Main { private double x1, y1; // 左上角坐标点 private double x2, y2; // 右下角坐标点 // 构造方法 public Main(double x1, double y1, double x2, double y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } // 计算矩形的面积 public double calculateArea() { double width = Math.abs(x2 - x1); double height = Math.abs(y2 - y1); return width * height; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double x1 = scanner.nextDouble(); double y1 = scanner.nextDouble(); double x2 = scanner.nextDouble(); double y2 = scanner.nextDouble(); Main rectangle = new Main(x1, y1, x2, y2); double area = rectangle.calculateArea(); System.out.println(String.format("%.2f", area)); scanner.close(); } }
展示了如何使用多个属性和构造函数来表示更复杂的形状。我们学到了如何使用Point类来表示坐标点,并且可以通过计算两点之间的差异来确定矩形的宽度和高度。
测验3-继承与多态
将测验1与测验2的类设计进行合并设计,抽象出Shape父类(抽象类),Circle及Rectangle作为子类
import java.util.Scanner; abstract class Shape { public abstract double calculateArea(); } class Circle extends Shape { private double radius; public Circle(double radius) { this.radius = radius; } @Override public double calculateArea() { return Math.PI * radius * radius; } } class Point { public double x; public double y; public Point(double x, double y) { this.x = x; this.y = y; } } class Rectangle extends Shape { private Point leftTopPoint; private Point lowerRightPoint; public Rectangle(Point leftTopPoint, Point lowerRightPoint) { this.leftTopPoint = leftTopPoint; this.lowerRightPoint = lowerRightPoint; } @Override public double calculateArea() { double width = Math.abs(lowerRightPoint.x - leftTopPoint.x); double height = Math.abs(lowerRightPoint.y - leftTopPoint.y); return width * height; } } public class Main { public static void printArea(Shape shape) { double area = shape.calculateArea(); System.out.println(String.format("%.2f", area)); } public static void main(String[] args) { Scanner input = new Scanner(System.in); int choice = input.nextInt(); switch (choice) { case 1: // Circle double radius = input.nextDouble(); Shape circle = new Circle(radius); printArea(circle); break; case 2: // Rectangle double x1 = input.nextDouble(); double y1 = input.nextDouble(); double x2 = input.nextDouble(); double y2 = input.nextDouble(); Point leftTopPoint = new Point(x1, y1); Point lowerRightPoint = new Point(x2, y2); Shape rectangle = new Rectangle(leftTopPoint, lowerRightPoint); printArea(rectangle); break; } input.close(); } }
代码定义了Shape接口和Circle、Rectangle类,其中Circle和Rectangle分别实现了Shape接口。
通过创建Circle和Rectangle对象,并调用它们的getArea方法,可以计算出不同形状的面积。
使用抽象类和接口来实现代码的灵活性和可扩展性。通过定义接口和抽象方法,可以确保每个具体类都提供所需的行为。
测验4-抽象类与接口
重构类设计,实现列表内图形的排序功能
import java.util.ArrayList; import java.util.Comparator; import java.util.Scanner; interface Shape { double getArea(); } class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } @Override public double getArea() { return Math.PI * radius * radius; } } class Point { public double x; public double y; public Point(double x, double y) { this.x = x; this.y = y; } } class Rectangle implements Shape { private Point leftTopPoint; private Point lowerRightPoint; public Rectangle(Point leftTopPoint, Point lowerRightPoint) { this.leftTopPoint = leftTopPoint; this.lowerRightPoint = lowerRightPoint; } @Override public double getArea() { double width = Math.abs(lowerRightPoint.x - leftTopPoint.x); double height = Math.abs(lowerRightPoint.y - leftTopPoint.y); return width * height; } } public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); ArrayList<Shape> list = new ArrayList<>(); int choice = input.nextInt(); while (choice != 0) { switch (choice) { case 1: // Circle double radius = input.nextDouble(); Shape circle = new Circle(radius); list.add(circle); break; case 2: // Rectangle double x1 = input.nextDouble(); double y1 = input.nextDouble(); double x2 = input.nextDouble(); double y2 = input.nextDouble(); Point leftTopPoint = new Point(x1, y1); Point lowerRightPoint = new Point(x2, y2); Shape rectangle = new Rectangle(leftTopPoint, lowerRightPoint); list.add(rectangle); break; } choice = input.nextInt(); } list.sort(Comparator.comparingDouble(Shape::getArea)); for (Shape shape : list) { System.out.print(String.format("%.2f", shape.getArea()) + " "); } input.close(); } }
使用动态列表和比较器来存储不同形状的对象,并根据面积进行排序。
使用ArrayList来存储Shape对象,用户可以连续输入不同形状的数据,直到输入0为止。然后,代码会根据每个形状的面积对列表进行排序,并按顺序打印出每个形状的面积。
使用动态列表来存储对象。我们还学到了如何使用Comparator.comparingDouble来基于形状的面积进行排序。
遇到的困难和需要改进的地方
代码中没有包含异常处理机制,例如当用户输入无效数据或非数字数据时,可能会引发异常。
可以进一步提高代码的复用性,例如将一些公共操作和方法提取到单独的类或工具类中。
对于复杂的要求,对类的构造和之间的联系不能很好的处理。在main中完成大部分的代码,不利于代码的维护,缺少异常处理。
心得体会
通过完成第四、第五次 PTA 作业以及本次期中考试,我进一步了解了 Java 的继承与多态的性质,并锻炼了构造合理代码结构的能力。这几次作业对我来说不仅仅是简单的任务,更是对我能力的一次考验。每次我都需不断修改自己的代码、调试、纠错、提交、再次调试、再次纠错...这一过程,可能并不是让人感到愉快的。但还是要继续,但经过这样的联系,对写代码能力有很大提升。
我觉得把Java学会的关键一点就是坚持练习。学习Java时每天必须保证一定量的练习,学习编程语言没有捷径可走。真的,只有每天反复操作了,经常写代码了,我们在遇到问题时才有一定的思路。学习编程语言需要一个比较漫长的阶段,不能一步登天,这需要一个过程,在这个过程中慢慢积累经验,扎实基础。不要满足于现状,要不断完善自己的知识体系,善于总结实践经验。要端正自己的学习态度,是主动去学,而不是被动!提高自学能力。学习编程的秘诀是:编程、编程、再编程。学习java这段时间,有时候会觉得有点苦,但是我觉得正是有了奋斗时的苦,才能换来学成后的甜。

浙公网安备 33010602011771号