第二次BLOG作业
对之前发布的PTA题目集4、5、6以及期中考试的总结性Blog:
- 前言:总结之前所涉及到的知识点、题量、难度情况;
- 知识点涉及:对类的职能分析,类的继承关系,以及对错误的抛出和错误处理(用try和catch简化主函数,使得主函数结构更加简化)
- 题量:菜单四和菜单五只有一题,均是菜单三的变式
- 难度:难度难,对类的职能划分要非常清晰,对不同类之间的方法要有很好的兼容性,以及对方法的返回值要求非常准确,否则将会导致报错。
- 设计与分析:重点对题目的提交源码进行分析,可参考SourceMonitor的生成报表内容以及PowerDesigner的相应类图,要有相应的解释和心得(做到有图有真相),本次Blog主要分析PTA中的菜单计价系列的题目以及期中考试的三道题目;
- 菜单四:
import java.text.ParseException; import java.time.DateTimeException; import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Objects; import java.util.Scanner; public class Main { public static boolean isNumeric(String string) { int intValue; try { intValue = Integer.parseInt(string); return true; } catch (NumberFormatException e) { return false; } } public static void main(String[] args) throws ParseException { Menu menu = new Menu(); ArrayList<Table> tables = new ArrayList<Table>(); Scanner input = new Scanner(System.in); String str1; int i; int portion, DishNumber; while (true) { // 输入菜单 Dish temp = new Dish(); int isRepeat = -1; str1 = input.nextLine(); if (str1.matches("[\\S]* [1-9][\\d]*")) { //判断是否与所给格式相同 String[] token = str1.split(" "); temp.name = token[0]; temp.Dishprice = Integer.parseInt(token[1]); if (temp.Dishprice > 300) { System.out.println(temp.name + " price out of range " + temp.Dishprice); continue; } temp.isT = false; isRepeat = menu.searchDish(temp.name); if (isRepeat != -1) { menu.dishs.remove(isRepeat); } menu.dishs.add(temp); } else if (str1.matches("[\\S]* [\\d]* T")) { String[] token = str1.split(" "); temp.name = token[0]; temp.Dishprice = Integer.parseInt(token[1]); if (temp.Dishprice > 300) { System.out.println(temp.name + " price out of range " + temp.Dishprice); continue; } temp.isT = true; menu.dishs.add(temp); } else if (str1.equals("end")) { break; } else if (str1.matches("tab.*")) { break; } else { System.out.println("wrong format"); } } while (!str1.equals("end")) { Table temp = new Table(); boolean isRepeat = false; int repeatNum = 0; if (str1.matches("table.*")) { if (str1.matches("table [1-9][\\d]* [\\d]*/[\\d][\\d]?/[\\d][\\d]? [\\d][\\d]?/[\\d][\\d]?/[\\d][\\d]?")) { String[] token = str1.split(" "); String[] Date = token[2].split("/"); String[] Time = token[3].split("/"); int[] intDate = new int[3]; int[] intTime = new int[3]; for (i = 0; i < 3; i++) { intDate[i] = Integer.parseInt(Date[i]); intTime[i] = Integer.parseInt(Time[i]); } temp.num = Integer.parseInt(token[1]); if (temp.num > 55) { System.out.println(temp.num + " table num out of range"); str1 = input.nextLine(); continue; } try { temp.time = LocalDateTime.of(intDate[0], intDate[1], intDate[2], intTime[0], intTime[1], intTime[2]); temp.getWeekDay(); } catch (DateTimeException e) { System.out.println(temp.num + " date error"); str1 = input.nextLine(); continue; } if (!(temp.time.isAfter(LocalDateTime.of(2022, 1, 1, 0, 0, 0)) && temp.time.isBefore(LocalDateTime.of(2024, 1, 1, 0, 0, 0)))) { System.out.println("not a valid time period"); str1 = input.nextLine(); continue; } // 判断桌号是否重复 if (temp.isOpen()) { for (i = 0; i < tables.size(); i++) { // 有重复的桌号 if (temp.num == tables.get(i).num && tables.get(i).isOpen()) { Duration duration = Duration.between(temp.time, tables.get(i).time); // 同一天 if (duration.toDays() == 0) { // 在周一到周五 if (temp.weekday > 0 && temp.weekday < 6) { // 在同一时间段 if (temp.time.getHour() < 15 && tables.get(i).time.getHour() < 15) { temp = tables.get(i); isRepeat = true; repeatNum = i; break; } } // 在周末 else { // 时间相差小于一小时 if (duration.toHours() < 3600) { temp = tables.get(i); repeatNum = i; isRepeat = true; break; } } } } } } if(!isRepeat) { System.out.println("table " + temp.num + ": "); } } else { System.out.println("wrong format"); str1 = input.nextLine(); continue; } // 本桌开始点菜 while (true) { str1 = input.nextLine(); if (str1.matches("[1-9][\\d]* [\\S]* [\\d] [1-9][\\d]*")) { String[] token = str1.split(" "); portion = Integer.parseInt(token[2]); DishNumber = Integer.parseInt(token[3]); if (temp.order.records.size() > 0) { if (Integer.parseInt( token[0]) <= temp.order.records.get(temp.order.records.size() - 1).orderNum) { System.out.println("record serial number sequence error"); continue; } } if (menu.searchDish(token[1]) == -1) { System.out.println(token[1] + " does not exist"); continue; } if (portion > 3 || portion < 1) { System.out.println(Integer.parseInt(token[0]) + " portion out of range " + portion); continue; } if (DishNumber > 15) { System.out.println(Integer.parseInt(token[0]) + " num out of range " + DishNumber); continue; } temp.od(menu, token[0], token[1], portion, DishNumber); } // 判断是否为删除订单 else if (str1.matches("[1-9][\\d]* delete")) { String[] token = str1.split(" "); temp.order.delARecordByOrderNum(Integer.parseInt(token[0])); } // 判断是否为夹杂菜单 else if (str1.matches("[\\S]* [\\d]*")) { System.out.println("invalid dish"); } else if (str1.matches("[\\S]* [\\d]* T")) { System.out.println("invalid dish"); continue; } // 判断是否为代点 else if (str1.matches("[\\d]* [\\d]* [\\S]* [\\d] [1-9][\\d]*")) { String[] token = str1.split(" "); // 判断代点桌号是否存在 boolean exist = false; for (Table table : tables) { if (table.num == Integer.parseInt(token[0])) { exist = true; break; } } if (exist) { System.out.print(Integer.parseInt(token[1]) + " table " + temp.num + " pay for table " + Integer.parseInt(token[0]) + " "); Record treat = new Record(); treat.d = menu.dishs.get(menu.searchDish(token[2])); portion = Integer.parseInt(token[3]); DishNumber = Integer.parseInt(token[4]); treat.portion = portion; treat.DishNumber = DishNumber; System.out.print(treat.getPrice() + "\n"); temp.sum += treat.getPrice(); } // 若不存在则输出内容 else { System.out.println("Table number :" + Integer.parseInt(token[0]) + " does not exist"); } } else if (str1.equals("end")) { break; } else if(str1.matches("ta.*")){ break; } else { System.out.println("wrong format"); } } } else if (str1.matches("t.*")) { isRepeat = true; temp = tables.get(tables.size()); while (true) { str1 = input.nextLine(); if (str1.matches("[1-9][\\d]* [\\S]* [\\d] [1-9][\\d]*")) { String[] token = str1.split(" "); portion = Integer.parseInt(token[2]); DishNumber = Integer.parseInt(token[3]); // 判断订单号是否由小到大排列 if (temp.order.records.size() > 0) { if (Integer.parseInt( token[0]) <= temp.order.records.get(temp.order.records.size() - 1).orderNum) { System.out.println("record serial number sequence error"); continue; } } if (menu.searchDish(token[1]) == -1) { System.out.println(token[1] + " does not exist"); continue; } if (portion > 3 || portion < 1) { System.out.println(Integer.parseInt(token[0]) + " portion out of range " + portion); continue; } if (DishNumber > 15) { System.out.println(Integer.parseInt(token[0]) + " num out of range " + DishNumber); continue; } temp.od(menu, token[0], token[1], portion, DishNumber); } // 判断是否为删除订单 else if (str1.matches("[1-9][\\d]* delete")) { String[] token = str1.split(" "); temp.order.delARecordByOrderNum(Integer.parseInt(token[0])); } // 判断是否为夹杂菜单 else if (str1.matches("[\\S]* [\\d]*")) { System.out.println("invalid dish"); } else if (str1.matches("[\\S]* [\\d]* T")) { System.out.println("invalid dish"); } // 判断是否为代点 else if (str1.matches("[\\d]* [\\d]* [\\S]* [\\d] [1-9][\\d]*")) { String[] token = str1.split(" "); // 判断代点桌号是否存在 boolean exist = false; for (Table table : tables) { if (table.num == Integer.parseInt(token[0])) { exist = true; break; } } if (exist) { System.out.print(Integer.parseInt(token[1]) + " table " + temp.num + " pay for table " + Integer.parseInt(token[0]) + " "); Record treat = new Record(); treat.d = menu.dishs.get(menu.searchDish(token[2])); portion = Integer.parseInt(token[3]); DishNumber = Integer.parseInt(token[4]); treat.portion = portion; treat.DishNumber = DishNumber; System.out.print(treat.getPrice() + "\n"); temp.sum += treat.getPrice(); } // 若不存在则输出内容 else { System.out.println("Table number :" + Integer.parseInt(token[0]) + " does not exist"); } } else if (str1.equals("end")) { break; } else { System.out.println("wrong format"); } } if (tables.size() != 0) { tables.get(tables.size() - 1).order.records.addAll(temp.order.records); } } else { str1 = input.nextLine(); continue; } // 本桌点菜结束,进入下一桌 if (isRepeat) { tables.remove(repeatNum); } temp.getSum(); tables.add(temp); } // 最终输出桌号订单信息 for (i = 0; i < tables.size(); i++) { if (tables.get(i).isOpen()) { System.out .println("table " + tables.get(i).num + ": " + tables.get(i).origSum + " " + tables.get(i).sum); } else System.out.println("table " + tables.get(i).num + " out of opening hours"); } } static class Record { int orderNum; //序号 Dish d; //菜品 int portion; //份额(1,2,3 小,中,大) int DishNumber; //配额(菜品c) boolean isDeleted = false; //判断删除 int getPrice() { //计价,计算本条菜品的价格 if (portion == 2) return (int) Math.round(1.5 * d.Dishprice) * DishNumber; else if (portion == 3) return 2 * d.Dishprice * DishNumber; else return d.Dishprice * DishNumber; } } static class Dish { //菜的类 String name; //菜品名称 int Dishprice; //菜品单价 boolean isT = false; //判断特色菜 } static class Order { Record addARecord(int orderNum, String dishName, int portion, int DishNumber, Menu menu) { //添加一条菜单信息到订单中 Record newRecord = new Record(); newRecord.orderNum = orderNum; newRecord.d = menu.dishs.get(menu.searchDish(dishName)); newRecord.portion = portion; newRecord.DishNumber = DishNumber; System.out.println(newRecord.orderNum + " " + newRecord.d.name + " " + newRecord.getPrice()); return newRecord; } //保存订单上每一道的记录,存放在数组里 ArrayList<Record> records = new ArrayList<>(); //根据序号删除一条记录 boolean delARecordByOrderNum(int orderNum) { int i = 0, flag = 0; for (i = 0; i < records.size(); i++) { if (records.get(i).orderNum == orderNum) { if (records.get(i).isDeleted == false) { records.get(i).isDeleted = true; } else { System.out.println("deduplication " + orderNum); } flag++; } } if (flag == 0) { System.out.println("delete error;"); return false; } return true; } //跟据序号查找一条记录 int searchRecord(String name) { for (int i = 0; i < records.size(); i++) { if (Objects.equals(records.get(i).d.name, name)) { return i; //返回序号 } } return -1; } } static class Menu { ArrayList<Dish> dishs = new ArrayList<Dish>(); int searchDish(String dishName) { for (int i = 0; i < dishs.size(); i++) { if (dishName.equals(dishs.get(i).name)) { return i; } } return -1; } Dish addDish(String dishName, int unit_price) { //添加一道菜品信息 Dish newDish = new Dish(); newDish.name = dishName; newDish.Dishprice = unit_price; return newDish; } } static class Table { Order order = new Order(); LocalDateTime time; int num; int weekday; long sum = 0; long origSum = 0; void od(Menu menu, String str1, String str2, int portion, int DishNumber) { { order.records.add(order.addARecord(Integer.parseInt(str1), str2, portion, DishNumber, menu)); } } boolean isOpen() { if (weekday > 0 && weekday < 6) { if (time.getHour() >= 17 && time.getHour() < 20) return true; if (time.getHour() == 20) { if (time.getMinute() <= 30) return true; } 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; } void getSum() { for (int i = 0; i < order.records.size(); i++) { if (!order.records.get(i).isDeleted) { origSum += order.records.get(i).getPrice(); if (order.records.get(i).d.isT) { if (weekday > 0 && weekday < 6) { sum += Math.round(order.records.get(i).getPrice() * 0.7); } else { sum += order.records.get(i).getPrice(); } } else { if (weekday > 0 && weekday < 6) { if (time.getHour() >= 17 && time.getHour() < 20) sum += Math.round(order.records.get(i).getPrice() * 0.8); if (time.getHour() == 20) { if (time.getMinute() <= 30) sum += Math.round(order.records.get(i).getPrice() * 0.8); } if (time.getHour() >= 10 && time.getHour() < 14) sum += Math.round(order.records.get(i).getPrice() * 0.6); if (time.getHour() == 14) { if (time.getMinute() <= 30) sum += Math.round(order.records.get(i).getPrice() * 0.6); } } else sum+=order.records.get(i).getPrice(); } } } } void getWeekDay() { weekday = time.getDayOfWeek().getValue(); } } } - 菜单五:
import java.time.LocalDate; import java.time.LocalTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Menu menu = new Menu(); menu.specialDish = new SpecialDish[100]; menu.commonDishes = new Dish[100]; Table table = new Table(); Print p = new Print(); Record records[] = new Record[100]; ArrayList<Table> tables = new ArrayList<>(); UserInformation u[] = new UserInformation[100]; Order order = new Order(); order.records = new Record[100]; int circulation = 0; //当前出现了几个桌 int UI = 0; boolean existOther = false; //在给其他人点菜的时候 boolean legalTable = false; //当前桌号是合法的,后续信息可以存储 while (true) { String signal = sc.nextLine(); if (signal.equals("end")) { if (circulation != 0) { table.order = order; tables.add(circulation - 1, table); } p.tables = tables; p.userInformation = u; p.printTableInformation(); p.printUserInformation(); break; } String str[] = signal.split(" "); //菜单的输入(普通菜) if (signal.matches("(\\S+)( )([^0])(\\d*)")) { int flag = 0; //当菜品出现多次的时候,价格要以最后一次为准 if(menu.commonDishesNum == 0){ menu.commonDishes[menu.commonDishesNum] = new Dish(); menu.addCommonDish(str[0], Integer.parseInt(str[1])); menu.commonDishesNum++; } else{ for (int i = 0; i < menu.commonDishesNum; i++) { if(str[0].equals(menu.commonDishes[i].name)){ flag = 1; menu.commonDishes[i].unit_price = Integer.parseInt(str[1]); break; } } if(flag == 0){ menu.commonDishes[menu.commonDishesNum] = new Dish(); menu.addCommonDish(str[0], Integer.parseInt(str[1])); menu.commonDishesNum++; } } } //菜单的输入(特殊菜) else if (signal.matches("(\\S+)( )(川菜|晋菜|浙菜)( )([^0])(\\d*)( )(T)")) { int flag = 0; if (menu.specialDishNum == 0) { menu.specialDish[menu.specialDishNum] = new SpecialDish(); menu.addSpecialDish(str[0], Integer.parseInt(str[2]), str[1]); menu.specialDishNum++; } else { for (int i = 0; i < menu.specialDishNum; i++) { if (str[0].equals(menu.specialDish[i].name)) { flag = 1; menu.specialDish[i].unit_price = Integer.parseInt(str[2]); break; } } if (flag == 0) { menu.specialDish[menu.specialDishNum] = new SpecialDish(); menu.addSpecialDish(str[0], Integer.parseInt(str[2]), str[1]); menu.specialDishNum++; } } } //桌号的输入 else if (signal.matches("(table)( )([^0])(\\d*)( )(:)( )(\\S{1,10})( )(180|181|189|133|135|136)(\\d{8})( )(\\d{4})(/)([1-9]|0[1-9]|\\d{2})(/)(\\d{1,2})( )(\\d{1,2})(/)(\\d{1,2})(/)(\\d{1,2})")) { if (circulation != 0) { table.order = order; tables.add(circulation - 1, table); table = new Table(); } table.addTableInformation(Integer.parseInt(str[1]), str[3], str[4], str[5], str[6]); if (!table.ifInTheWorkTime()) { System.out.println("table " + table.tableNum + " out of opening hours"); continue; } legalTable = true; order = new Order(); order.records = new Record[100]; if (circulation == 0) { u[UI] = new UserInformation(); u[UI].userName = table.userName; u[UI].telephoneNum = table.telephoneNum; UI++; p.userInformationI = UI; } //需要判断人名和电话是否已经存在了 else { int flag = 0; for (int i = 0; i < UI; i++) { if (str[3].equals(u[i].userName) && str[4].equals(u[i].telephoneNum)) { flag = 1; break; } } if (flag == 0) { u[UI] = new UserInformation(); u[UI].userName = str[3]; u[UI].telephoneNum = str[4]; UI++; p.userInformationI = UI; } } circulation++; System.out.println("table " + str[1] + ": "); } //订单上普通菜品的输入 else if (signal.matches("([^0])(\\d*)( )(\\S+)( )([^0])(\\d*)( )([^0])(\\d*)")) { if (!legalTable) { continue; } if (menu.searchCommonDish(str[1]) != null) { order.records[order.recordNum] = new Record(); order.addACommonRecord(Integer.parseInt(str[0]), str[1], Integer.parseInt(str[2]), Integer.parseInt(str[3]), menu); order.records[order.recordNum].ifSpecial = false; System.out.println(order.records[order.recordNum].orderNum + " " + order.records[order.recordNum].d.name + " " + order.records[order.recordNum].gerARecordPrice()); order.recordNum++; } else { System.out.println(str[1] + " does not exist"); } } //订单上特殊菜的输入 else if (signal.matches("([^0])(\\d*)( )(\\S+)( )(\\d+)( )([^0])(\\d*)( )([^0])(\\d*)")) { if (!legalTable) { continue; } if (menu.searchSpecialDish(str[1]) != null) { if (((menu.searchSpecialDish(str[1]).taste.equals("川菜") && Integer.parseInt(str[2]) >= 0 && Integer.parseInt(str[2]) <= 5) || (menu.searchSpecialDish(str[1]).taste.equals("晋菜") && Integer.parseInt(str[2]) >= 0 && Integer.parseInt(str[2]) <= 4) || (menu.searchSpecialDish(str[1]).taste.equals("浙菜") && Integer.parseInt(str[2]) >= 0 && Integer.parseInt(str[2]) <= 3))) { order.records[order.recordNum] = new Record(); order.addASpecialRecord(Integer.parseInt(str[0]), str[1], Integer.parseInt(str[3]), Integer.parseInt(str[4]), menu, Integer.parseInt(str[2]), existOther); order.records[order.recordNum].ifSpecial = true; order.records[order.recordNum].d = menu.searchSpecialDish(str[1]); System.out.println(order.records[order.recordNum].orderNum + " " + order.records[order.recordNum].d.name + " " + order.records[order.recordNum].gerARecordPrice()); order.recordNum++; } } else { System.out.println(str[1] + " does not exist"); continue; } order.printTasteOutOf(menu, str[1], Integer.parseInt(str[2])); } //删除记录 else if (signal.matches("([^0])(\\d*)( )(delete)")) { if (!legalTable) { continue; } if (order.ifCanFindTheRecordNum(Integer.parseInt(str[0]))) { order.delARecordByOrderNum(Integer.parseInt(str[0])); } else { System.out.println("delete error;"); } } //代点菜(普通菜) else if (signal.matches("([^0])(\\d*)( )([^0](\\d*)( )(\\S+)( )(\\d+)( )(\\d+))")) { if (!legalTable) { continue; } int substituteTableNum = Integer.parseInt(str[0]); for (int i = 0; i < circulation - 1; i++) { if (substituteTableNum == tables.get(i).tableNum) { if (menu.searchCommonDish(str[2]) != null) { order.records[order.recordNum] = new Record(); order.addACommonRecord(Integer.parseInt(str[1]), str[2], Integer.parseInt(str[3]), Integer.parseInt(str[4]), menu); order.records[order.recordNum].ifSpecial = false; System.out.println(str[1] + " table " + table.tableNum + " pay for table " + str[0] + " " + order.records[order.recordNum].gerARecordPrice()); order.recordNum++; } break; } } } //代点菜(特殊菜) else if (signal.matches("([^0])(\\d*)( )([^0](\\d*)( )(\\S+)( )(\\d+)( )(\\d+)( )(\\d+))")) { if (!legalTable) { continue; } int substituteTableNum = Integer.parseInt(str[0]); for (int i = 0; i < circulation - 1; i++) { if (tables.get(i).tableNum == substituteTableNum) { if (menu.searchSpecialDish(str[2]) != null) { if (((menu.searchSpecialDish(str[2]).taste.equals("川菜") && Integer.parseInt(str[3]) >= 0 && Integer.parseInt(str[3]) <= 5) || (menu.searchSpecialDish(str[2]).taste.equals("晋菜") && Integer.parseInt(str[3]) >= 0 && Integer.parseInt(str[3]) <= 4) || (menu.searchSpecialDish(str[2]).taste.equals("浙菜") && Integer.parseInt(str[3]) >= 0 && Integer.parseInt(str[3]) <= 3))) { order.records[order.recordNum] = new Record(); order.addASpecialRecord(Integer.parseInt(str[1]), str[2], Integer.parseInt(str[4]), Integer.parseInt(str[5]), menu, Integer.parseInt(str[3]), !existOther); order.records[order.recordNum].ifSpecial = true; order.records[order.recordNum].d = menu.searchSpecialDish(str[2]); System.out.println(str[1] + " table " + table.tableNum + " pay for table " + str[0] + " " + order.records[order.recordNum].gerARecordPrice()); tables.get(i).giveTheTasteToAnother(str[2], Integer.parseInt(str[3]), Integer.parseInt(str[5]), menu); order.recordNum++; } } break; } } } else { System.out.println("wrong format"); } } } } class Menu { Dish commonDishes[]; SpecialDish specialDish[]; int commonDishesNum = 0; int specialDishNum = 0; public void addCommonDish(String dishName, int unit_price) { commonDishes[commonDishesNum].name = dishName; commonDishes[commonDishesNum].unit_price = unit_price; } public void addSpecialDish(String dishName, int unit_price, String taste) { specialDish[specialDishNum].name = dishName; specialDish[specialDishNum].unit_price = unit_price; specialDish[specialDishNum].taste = taste; } public Dish searchCommonDish(String dishName) { for (int i = 0; i < commonDishesNum; i++) { if (dishName.equals(commonDishes[i].name)) { return commonDishes[i]; } } return null; } public SpecialDish searchSpecialDish(String dishName) { for (int i = 0; i < specialDishNum; i++) { if (dishName.equals(specialDish[i].name)) { return specialDish[i]; } } return null; } } class Order { int allOfCommonRecordPrice = 0; int allOfSpecialRecordPrice = 0; Record records[]; int recordNum = 0; public void addACommonRecord(int orderNum, String dishName, int portion, int count, Menu menu) { records[recordNum].orderNum = orderNum; records[recordNum].portion = portion; records[recordNum].count = count; records[recordNum].d = menu.searchCommonDish(dishName); } public void addASpecialRecord(int orderNum, String dishName, int portion, int count, Menu menu, int tasteDegree, boolean existOther) { records[recordNum].orderNum = orderNum; records[recordNum].portion = portion; records[recordNum].count = count; records[recordNum].specialDish = menu.searchSpecialDish(dishName); if (existOther) { records[recordNum].spicyDegree = -1; records[recordNum].acidityDegree = -1; records[recordNum].sweetnessDegree = -1; } else { if (menu.searchSpecialDish(dishName).taste.equals("川菜")) { records[recordNum].spicyDegree = tasteDegree; } else if (menu.searchSpecialDish(dishName).taste.equals("晋菜")) { records[recordNum].acidityDegree = tasteDegree; } else if (menu.searchSpecialDish(dishName).taste.equals("浙菜")) { records[recordNum].sweetnessDegree = tasteDegree; } } } public void getAllRecordsPrice() { for (int i = 0; i < recordNum; i++) { if (records[i].ifSpecial) { allOfSpecialRecordPrice += records[i].gerARecordPrice(); } else { allOfCommonRecordPrice += records[i].gerARecordPrice(); } } } public int getTheEndPrice(double specialDisCount, double commonDiscount) { int endPrice = 0; for (int i = 0; i < recordNum; i++) { if (records[i].ifSpecial) { endPrice += Math.round(specialDisCount * records[i].gerARecordPrice()); } else { endPrice += Math.round(commonDiscount * records[i].gerARecordPrice()); } } return endPrice; } public void delARecordByOrderNum(int orderNum) { for (int i = 0; i < recordNum; i++) { if (records[i].orderNum == orderNum) { records[i].count = 0; } } } public boolean ifCanFindTheRecordNum(int deleteNum) { for (int i = 0; i < recordNum; i++) { if (records[i].orderNum == deleteNum) { return true; } } return false; } public void printTasteOutOf(Menu menu, String dishName, int degree) { SpecialDish s = menu.searchSpecialDish(dishName); if (s != null) { if (s.taste.equals("川菜")) { if (degree > 5) { System.out.println("spicy num out of range :" + degree); } } else if (s.taste.equals("晋菜")) { if (degree > 4) { System.out.println("acidity num out of range :" + degree); } } else if (s.taste.equals("浙菜")) { if (degree > 3) { System.out.println("sweetness num out of range :" + degree); } } } } } class Print { ArrayList<Table> tables = new ArrayList<>(); UserInformation userInformation[]; int userInformationI; public void printTableInformation() { for (Table table : tables) { table.getTasteAverage(); table.order.getAllRecordsPrice(); System.out.print("table " + table.tableNum + ": " + (table.order.allOfCommonRecordPrice + table.order.allOfSpecialRecordPrice)+" "+table.getTotalTablePrice()); int degreeFlag = 0; //用来确定格式的 if (table.order.allOfSpecialRecordPrice != 0) { System.out.print(" "); if (table.spicyCount != 0) { degreeFlag = 1; System.out.print("川菜" + " " + (int)table.spicyCount + " " + table.getSpicyConcreteDegree()); } if (table.acidityCount != 0) { if (degreeFlag == 1) { System.out.print(" "); } degreeFlag = 1; System.out.print("晋菜" + " " + (int)table.acidityCount + " " + table.getConcreteAcidityDegree()); } if (table.sweetnessCount != 0) { if (degreeFlag == 1) { System.out.print(" "); } System.out.print("浙菜" + " " + (int)table.sweetnessCount + " " + table.getConcreteSweetnessDegree()); } } else { System.out.print(" "); } System.out.println(); } } public void adjustTheOrderOfTheUsers() { for (int i = 0; i < userInformationI; i++) { for (Table table : tables) { if (table.userName.equals(userInformation[i].userName) && table.telephoneNum.equals(userInformation[i].telephoneNum)) { userInformation[i].userPrice += table.getTotalTablePrice(); } } } for (int i = 0; i < userInformationI - 1; i++) { for (int i1 = 0; i1 < userInformationI - 1 - i; i1++) { if (userInformation[i1].userName.length() < userInformation[i1 + 1].userName.length()) { UserInformation u = null; u = userInformation[i1]; userInformation[i1] = userInformation[i1 + 1]; userInformation[i1 + 1] = u; } } } for (int i = 0; i < userInformationI - 1; i++) { for (int i1 = 0; i1 < userInformationI - 1 - i; i1++) { if (userInformation[i1].userName.compareTo(userInformation[i1 + 1].userName) > 0) { UserInformation u = null; u = userInformation[i1]; userInformation[i1] = userInformation[i1 + 1]; userInformation[i1 + 1] = u; } } } } public void printUserInformation() { adjustTheOrderOfTheUsers(); for (int i = 0; i < userInformationI; i++) { System.out.println(userInformation[i].userName + " " + userInformation[i].telephoneNum + " " + userInformation[i].userPrice); } } } class Record { Dish d; //菜品 SpecialDish specialDish; int orderNum = 0; int count = 0; //订单上的份数 int portion = 0; //份额(1/2/3代表小/中/大份) int spicyDegree = 0; int acidityDegree = 0; int sweetnessDegree = 0; boolean ifSpecial = false; public int gerARecordPrice() { return count * d.getPrice(portion); } } class SpecialDish extends Dish{ String taste; } class Table { String userName; int tableNum; String dayTime; String secondTime; String telephoneNum; Order order; double commonDiscount; double specialDiscount; int spicyAverage; int acidityAverage; int sweetnessAverage; double spicyCount; double acidityCount; double sweetnessCount; public void addTableInformation(int tableNum, String userName, String telephoneNum, String dayTime, String secondTime) { this.tableNum = tableNum; this.userName = userName; this.telephoneNum = telephoneNum; this.dayTime = dayTime; this.secondTime = secondTime; } public int getTotalTablePrice() { return order.getTheEndPrice(specialDiscount, commonDiscount); } public boolean ifInTheWorkTime() { String day[] = dayTime.split("/"); String time[] = secondTime.split("/"); LocalDate d1 = LocalDate.of(Integer.parseInt(day[0]), Integer.parseInt(day[1]), Integer.parseInt(day[2])); LocalTime d2 = LocalTime.of(Integer.parseInt(time[0]), Integer.parseInt(time[1]), Integer.parseInt(time[2])); LocalTime dRelaxStart = LocalTime.of(9, 30); LocalTime dRelaxEnd = LocalTime.of(21, 30); LocalTime dWorkStart1 = LocalTime.of(10, 30); LocalTime dWorkStart2 = LocalTime.of(17, 0); LocalTime dWorkEnd1 = LocalTime.of(14, 30); LocalTime dWorkEnd2 = LocalTime.of(20, 30); int Day = d1.getDayOfWeek().getValue(); if (Day == 6 || Day == 7) { if (d2.isAfter(dRelaxEnd) || d2.isBefore(dRelaxStart)) { return false; } else { specialDiscount = 1; commonDiscount = 1; return true; } } else { if ((d2.isAfter(dWorkStart1) && d2.isBefore(dWorkEnd1)) || (d2.until(dWorkStart1, ChronoUnit.SECONDS) == 0 || d2.until(dWorkEnd1, ChronoUnit.SECONDS) == 0)) { commonDiscount = 0.6; specialDiscount = 0.7; return true; } else if ((d2.isAfter(dWorkStart2) && d2.isBefore(dWorkEnd2)) || (d2.until(dWorkStart2, ChronoUnit.SECONDS) == 0 || d2.until(dWorkEnd2, ChronoUnit.SECONDS) == 0)) { commonDiscount = 0.8; specialDiscount = 0.7; return true; } else { return false; } } } public String getSpicyConcreteDegree() { if (spicyAverage == 0) { return "不辣"; } else if (spicyAverage == 1) { return "微辣"; } else if (spicyAverage == 2) { return "稍辣"; } else if (spicyAverage == 3) { return "辣"; } else if (spicyAverage == 4) { return "很辣"; } else if (spicyAverage == 5) { return "爆辣"; } return null; } public String getConcreteAcidityDegree() { if (acidityAverage == 0) { return "不酸"; } else if (acidityAverage == 1) { return "微酸"; } else if (acidityAverage == 2) { return "稍酸"; } else if (acidityAverage == 3) { return "酸"; } else if (acidityAverage == 4) { return "很酸"; } return null; } public String getConcreteSweetnessDegree() { if (sweetnessAverage == 0) { return "不甜"; } else if (sweetnessAverage == 1) { return "微甜"; } else if (sweetnessAverage == 2) { return "稍甜"; } else if (sweetnessAverage == 3) { return "甜"; } return null; } public void getTasteAverage() { //double spicyAver = 0, acidityAver = 0, sweetnessAver = 0; for (int i = 0; i < order.recordNum; i++) { if (order.records[i].ifSpecial) { if (order.records[i].specialDish.taste.equals("川菜") && order.records[i].spicyDegree != -1) { spicyAverage += order.records[i].spicyDegree * order.records[i].count; spicyCount += order.records[i].count; } else if (order.records[i].specialDish.taste.equals("晋菜") && order.records[i].acidityDegree != -1) { acidityAverage += order.records[i].acidityDegree * order.records[i].count; acidityCount += order.records[i].count; } else if (order.records[i].specialDish.taste.equals("浙菜") && order.records[i].sweetnessDegree != -1) { sweetnessAverage += order.records[i].sweetnessDegree * order.records[i].count; sweetnessCount += order.records[i].count; } } } if (spicyCount != 0) { spicyAverage = (int) Math.round(spicyAverage / spicyCount); } if (acidityCount != 0) { acidityAverage = (int) Math.round(acidityAverage / acidityCount); } if (sweetnessCount != 0) { sweetnessAverage = (int) Math.round(sweetnessAverage / sweetnessCount); } } public void giveTheTasteToAnother(String dishName, int degree, int count, Menu menu) { if (menu.searchSpecialDish(dishName).taste.equals("川菜")) { spicyAverage += degree * count; spicyCount += count; } if (menu.searchSpecialDish(dishName).taste.equals("晋菜")) { acidityAverage += degree * count; acidityCount += count; } if (menu.searchSpecialDish(dishName).taste.equals("浙菜")) { sweetnessAverage += degree * count; sweetnessCount += count; } } } class UserInformation { String userName; String telephoneNum; int userPrice; } class Dish { //对应菜谱上一道菜的信息。 String name; //菜品名称 int unit_price; //单价 boolean special; //是否是特殊菜 public int getPrice(int portion) { //计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份) double price = 0; if (portion == 1) { price = unit_price; } else if (portion == 2) { price = unit_price * 1.5; } else if (portion == 3) { price = unit_price * 2; } int price1 = (int) run(price); return price1; } double run(double num) { double a = Math.signum(num); //判断是正数负数还是0,负数返回-1.0,正数返回1.0 if (a < 0.0) return 0.0 - Math.round(Math.abs(num)); return Math.round(num); } } - 期中考试:
导入需要使用的Scanner类,它能够从控制台读取用户输入。
创建一个名为Circle的类,并在类中定义一个私有属性radius表示圆的半径。
在Circle类中编写一个构造方法,用于初始化圆的半径。
在Circle类中编写一个公共方法getArea,用于计算圆的面积。面积的计算公式为π * 半径 * 半径,其中π可以使用Math.PI获取。
在Circle类的main方法中,先创建一个Scanner对象用于读取用户的输入。
使用scanner.nextDouble()方法从控制台读取一个double类型的值,即圆的半径。
关闭Scanner对象,释放资源。
判断输入的半径是否合法。如果小于等于0,则输出"Wrong Format"。
如果输入的半径合法,则创建一个Circle对象,并将输入的半径作为参数传递给构造方法。
使用getArea方法计算圆的面积,并将结果保留两位小数输出,使用System.out.printf("%.2f", area)实现。
程序结束。
这份代码使用面向对象的思想,将圆形的属性(半径)和行为(计算面积)封装在一个类中,使得代码结构更加清晰和可维护。同时,通过使用Scanner类从控制台读取用户输入,可以方便地获取需要的数值进行计算import java.util.Scanner; public class Main { private double radius; public Main(double radius) { this.radius = radius; } public double getArea() { return Math.PI * radius * radius; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double radius = scanner.nextDouble(); scanner.close(); if (radius <= 0) { System.out.println("Wrong Format"); } else { Main circle = new Main(radius); double area = circle.getArea(); System.out.printf("%.2f", area); } } }导入必要的类:导入java.util.Scanner类,以便从控制台获取用户的输入。
定义Main类:创建一个名为Main的类,用于表示矩形对象。
定义属性:在Main类中定义私有属性x1、y1、x2、y2,分别表示矩形的左上角和右下角的坐标。
定义构造方法:创建具有四个参数的构造方法,用于初始化矩形对象的坐标属性。
定义计算面积的方法:在Main类中定义一个公共方法getArea(),用于计算矩形的面积。该方法通过计算矩形的宽度(width)和高度(height),并返回二者相乘的结果,即矩形的面积。
定义main()方法:在Main类中定义main()方法作为程序的入口点。
创建Scanner对象:在main()方法中创建一个Scanner对象scanner,用于从控制台读取用户输入。
获取用户输入:使用scanner.nextDouble()方法分别获取用户输入的四个浮点数,分别表示矩形的两个坐标点的x和y值。
关闭Scanner对象:在获取用户输入后,使用scanner.close()方法关闭Scanner对象,以释放资源。
创建Main对象并计算面积:使用获取到的用户输入的坐标值创建一个Main对象rectangle。然后调用rectangle.getArea()方法计算矩形的面积。
格式化输出矩形的面积:使用System.out.printf()方法将计算得到的矩形面积输出到控制台,并保留两位小数。
import java.util.Scanner; public class Main { private double x1; private double y1; private double x2; private double 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 getArea() { 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(); scanner.close(); Main rectangle = new Main(x1, y1, x2, y2); double area = rectangle.getArea(); System.out.printf("%.2f", area); } }第三题:首先,定义了一个Main类作为程序的入口点。
在main()方法中,通过创建一个Scanner对象来读取用户输入的选择(1或2)。
使用switch语句根据选择的值,进入不同的分支。
若选择为1,表示选择了计算圆的面积。接着读取用户输入的圆的半径,并创建Circle对象。
若选择为2,表示选择了计算矩形的面积。接着按顺序读取用户输入的矩形的左上角和右下角坐标,并创建Rectangle对象。
调用printArea()方法并传入相应的图形对象,以打印出图形的面积。
printArea()方法接受一个Shape类型的参数,该参数可以是Circle对象或Rectangle对象,因为它们都实现了Shape接口。通过调用对象的getArea()方法获取面积,并使用System.out.printf()方法格式化输出面积,保留两位小数。
最后,通过input.close()关闭Scanner对象以释放资源。
整个代码设计遵循了面向对象编程的原则,利用接口、多态和类的继承关系,使得代码结构清晰、易于扩展和维护。通过封装不同的对象和方法,实现了对不同图形面积的计算和输出import java.util.Scanner; public class Main { 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); Rectangle rectangle = new Rectangle(leftTopPoint, lowerRightPoint); printArea(rectangle); break; } input.close(); } public static void printArea(Shape shape) { double area = shape.getArea(); System.out.printf("%.2f%n", area); } } interface Shape { double getArea(); } class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } public double getArea() { return Math.PI * radius * radius; } } class Rectangle implements Shape { private Point leftTopPoint; private Point lowerRightPoint; public Rectangle(Point leftTopPoint, Point lowerRightPoint) { this.leftTopPoint = leftTopPoint; this.lowerRightPoint = lowerRightPoint; } public double getArea() { double width = lowerRightPoint.getX() - leftTopPoint.getX(); double height = leftTopPoint.getY() - lowerRightPoint.getY(); return width * height; } } class Point { private double x; private double y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } } - 第四题:
在主类Main中,首先创建一个Scanner对象用于接收用户的输入,并创建一个空的ArrayList<Shape>对象用于存储图形。
通过用户输入的选项(1代表圆形,2代表矩形,0代表结束输入),在循环中进行不同的处理:
若用户选择1(圆形),则读取用户输入的半径,并创建一个Circle对象,并将其添加到图形列表中。
若用户选择2(矩形),则依次读取用户输入的四个点的坐标,并创建一个Rectangle对象,并将其添加到图形列表中。
用户选择0时,表示输入结束,跳出循环。
使用list.sort(Comparator.naturalOrder())对图形列表进行排序。由于Shape接口实现了Comparable接口并重写了compareTo方法,所以可以直接使用列表的sort方法进行排序。
使用循环遍历列表中的每个图形对象,并调用其getArea()方法打印出面积。
关闭Scanner对象。
整体思路是通过用户输入构建不同类型的图形对象,并将这些对象添加到列表中。然后使用sort方法对列表进行排序,排序依据是图形的面积大小。最后,按顺序遍历列表中的图形对象,并打印出它们的面积。通过这种方式,实现了按照图形面积进行排序的功能。import java.util.ArrayList; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); 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); Rectangle rectangle = new Rectangle(leftTopPoint, lowerRightPoint); list.add(rectangle); break; } choice = input.nextInt(); } list.sort(Comparator.naturalOrder()); // 使用默认的升序排序 for (int i = 0; i < list.size(); i++) { System.out.print(String.format("%.2f", list.get(i).getArea()) + " "); } input.close(); } } interface Shape extends Comparable<Shape> { double getArea(); } class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } public double getArea() { return Math.PI * radius * radius; } public int compareTo(Shape other) { return Double.compare(this.getArea(), other.getArea()); } } class Rectangle implements Shape { private Point leftTopPoint; private Point lowerRightPoint; public Rectangle(Point leftTopPoint, Point lowerRightPoint) { this.leftTopPoint = leftTopPoint; this.lowerRightPoint = lowerRightPoint; } public double getArea() { double width = lowerRightPoint.getX() - leftTopPoint.getX(); double height = leftTopPoint.getY() - lowerRightPoint.getY(); return width * height; } public int compareTo(Shape other) { return Double.compare(this.getArea(), other.getArea()); } } class Point { private double x; private double y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } }
- 菜单四:
- 采坑心得:对源码的提交过程中出现的问题及心得进行总结,务必做到详实,拿数据、源码及测试结果说话,切忌假大空;
- 先做类图,将题目分析,将结构设计好,将各类的职能划分好,再进行编程,提高编程效率。
![]()
- 先做类图,将题目分析,将结构设计好,将各类的职能划分好,再进行编程,提高编程效率。
- 改进建议:对代码的编程要有一定的伸缩性,扩展性和衍生性做到可持续改进
- 总结:
- 学会了用try和catch语句;
- 学会了继承类的运用;
- 学会了编程基本思路,先创建类图,再进行编程,提高编程的效率。


浙公网安备 33010602011771号