一、前言
第四次题目集,主要是菜单计价程序,难度逐渐提高,难度不是很高。
第五次题目集,只有一道菜单计价程序4,这道题是在菜单计价程序3的基础上添加了时间处理,使得程序整体难度提升很大
第六次题目集,也只有一道菜单计价程序5,这道题也是以菜单计价程序3为基础,添加了特色菜的处理,难度相较于菜单计价程序3有所增加,但相较于菜单计价程序4难度还是小一点。
期中考试题考了类的设计、继承和多态、抽象类和接口,都是一些知识的简单应用,没有什么复杂的设计思路。
二、设计与分析
第四次题目集7-1菜单计价3:
import java.util.Scanner; import java.util.Calendar; import java.lang.Math; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Menu menu = new Menu();//菜单初始化 Restaurant restaurant = new Restaurant();//订单初始化 int ordering = 0; while(true) { String input = scanner.nextLine();//输入 if (input.equals("end")) { break; } String[] str = input.split(" "); if(str[0].equals("table")){ restaurant.addTable(Integer.parseInt(str[1]), str[2], str[3]);//添加tableNum号桌 ordering = Integer.parseInt(str[1]);//记录点单桌号 System.out.println("table " + ordering + ": "); continue; }else if(str[1].equals("delete")) {//第二段为delete,删除 restaurant.searthTable(ordering).delARecordByOrderNum(Integer.parseInt(str[0])); continue; }else if(str[0].matches("\\d+") && !str[1].matches("\\d+")) {//第一段为数字,添加订单 restaurant.searthTable(ordering).addARecord( Integer.parseInt(str[0]), str[1], Integer.parseInt(str[2]), Integer.parseInt(str[3]), menu); continue; }else if(str.length == 5){ restaurant.searthTable(ordering).substituteARecord(//代点 Integer.parseInt(str[0]), Integer.parseInt(str[1]), str[2], Integer.parseInt(str[3]), Integer.parseInt(str[4]), menu); }else{//添加菜单 menu.addDish(str[0], Integer.parseInt(str[1])); } }//while for(Order re : restaurant.getRestaurant()){ if(re!=null){ if(re.getTime().getDiscount() == 0){ System.out.println("table " + re.getTableNum() + " out of opening hours");//不在运营时间 }else{ System.out.println("table " + re.getTableNum() + ": " + re.getTotalPrice());//总价 } } } } } //菜品类 class Dish { private String name;//菜品名称 private int unit_price; // 单价 public Dish(String name, int unitPrice) {//记录dish this.name = name; this.unit_price = unitPrice; } public int getPrice(int portion){//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份) if (portion == 1) { // 小份 return unit_price; } else if (portion == 2) { // 中份 return (int) Math.round(unit_price * 1.5); } else if (portion == 3) { // 大份 return unit_price * 2; } else { return -1; // 非法份额 } } public void setUnit_price(int price) {//设置底价 this.unit_price = price; } public int getUnit_price() {//获得底价 return unit_price; } public String getName() {//获取菜名 return name; } public void setName(String name) {//设置菜名 this.name = name; } } //菜谱类 class Menu { private Dish[] dishs ;//菜品数组,保存所有菜品信息 private int i; public Menu() { this.dishs = new Dish[10]; this.i = 0; } public Dish searthDish(String dishName){//根据菜名在菜谱中查找菜品信息,返回Dish对象。 for(Dish dish : dishs) { if(dish!=null&&dish.getName().equals(dishName)) { return dish; } } return null; } public void addDish(String dishName,int unit_price){//添加一道菜品信息 for (Dish dish : dishs) { if(dish !=null && dish.getName().equals(dishName)){ dish.setUnit_price(unit_price); return; } } Dish dish = new Dish(dishName, unit_price); if (i < dishs.length) { dishs[i++] = dish; } //else {System.out.println("菜品已达到最大数量,无法继续添加。");} } } //点菜记录类 class Record { private int orderNum;//序号\ private Dish d;//菜品\ private int portion;//份额(1/2/3代表小/中/大份)\ private int num;//份数 private boolean delete;//删除标志 public Record(int orderNum, String dishName, int portion,int num,Menu menu) { this.orderNum = orderNum; this.portion = portion; this.num = num; this.d = menu.searthDish(dishName); this.delete = false; } public int getPrice(){//计价,计算本条记录的价格\ return num*d.getPrice(portion); } public int getOrderNum() { return orderNum; } public void setOrderNum(int orderNum) { this.orderNum = orderNum; } public boolean getDelete() { return delete; } public void setDelete(boolean delete) { this.delete = delete; } public Dish getDish() { return d; } } //订单类 class Order { private Record[] records;//保存订单上每一道的记录 private int tableNum;//桌号 private Time time;//点餐时间 private int n=0;//点餐时间 public Order(int tableNum,Time time) { this.records = new Record[10]; this.tableNum=tableNum; this.time=time; } public Record[] getRecord() { return records; } public int getTotalPrice(){//计算订单的总价 int totalPrice = 0; for (Record record : records) { if (record != null&&!record.getDelete()) { totalPrice += record.getPrice(); } } return (int)Math.round(totalPrice*time.getDiscount()/10.0);//四舍五入 } public void substituteARecord(int subTableNum, int orderNum,String dishName,int portion,int num,Menu menu){//代点一条菜品信息到订单中。 if (num >= 0 && num < records.length) { if(menu.searthDish(dishName) == null){ System.out.println(dishName + " does not exist");//菜单中没找到该菜 }else { Record record = new Record(orderNum, dishName, portion, num, menu); records[n++] = record; int totalPrice = record.getPrice(); System.out.println(orderNum + " table " + tableNum + " pay for table " + subTableNum + " " + totalPrice); } } // else {System.out.println("无法添加记录,序号超出范围。");} } public void addARecord(int orderNum,String dishName,int portion,int num,Menu menu){//添加一条菜品信息到订单中。 if (num >= 0 && num < records.length) { if(menu.searthDish(dishName) == null){ System.out.println(dishName + " does not exist"); }else { Record record = new Record(orderNum, dishName, portion, num, menu); records[n++] = record; int totalPrice = record.getPrice(); System.out.println(orderNum + " " + dishName + " " + totalPrice); } } // else {System.out.println("无法添加记录,序号超出范围。");} } public void delARecordByOrderNum(int orderNum){//根据序号删除一条记录 if(findRecordByNum(orderNum)==null){ System.out.println("delete error;"); }else{ findRecordByNum(orderNum).setDelete(true); } } public Record findRecordByNum(int orderNum){//根据序号查找一条记录 for (Record record : records) { if (record != null && record.getOrderNum() == orderNum) { return record; } } return null; } public int getTableNum(){ return tableNum; } public void setTableNum(int tableNum){ this.tableNum=tableNum; } public Time getTime(){ return time; } public void setTime(Time time){ this.time=time; } } class Time{ private int year; private int month; private int day; private int hour; private int minute; private int seconds; public Time(int year,int month,int day,int hour,int minute,int seconds){ this.year=year; this.month=month; this.day=day; this.hour=hour; this.minute=minute; this.seconds=seconds; } public int getDiscount(){//判断是否营业并返回折扣 Calendar time = Calendar.getInstance(); time.set(year, month-1, day, hour, minute, seconds); int weekDay = time.get(Calendar.DAY_OF_WEEK); int moment = hour*60*60+minute*60+seconds; if(weekDay>=2 && weekDay<=6){//周一到周五 if(moment>=61200 && moment<=73800){//17:00--20:30 return 8; }else if(moment>=37800 && moment<=52200){//10:30--14:30 return 6; }else { return 0; } }else{ if(moment>=34200 && moment<=77400){//9:30--21:30 return 10; }else{ return 0; } } } } class Restaurant{ private Order[] tables; public Restaurant(){ this.tables = new Order[10]; } public void addTable(int tableNum, String time1, String time2) { String[] str1 = time1.split("/"); String[] str2 = time2.split("/"); int year = Integer.parseInt(str1[0]); int month = Integer.parseInt(str1[1]); int day = Integer.parseInt(str1[2]); int hour = Integer.parseInt(str2[0]); int minute = Integer.parseInt(str2[1]); int seconds = Integer.parseInt(str2[2]); Time time = new Time(year, month, day, hour, minute, seconds); for (Order table : tables) { if(table !=null && table.getTableNum()==tableNum){ table.setTime(time); return; } } Order table = new Order(tableNum,time); if (tableNum < tables.length) { tables[tableNum] = table; } // else {System.out.println("无法添加桌子,达到最大容量。");} } public Order searthTable(int tableNum){ return tables[tableNum]; } public Order[] getRestaurant(){ return tables; } }
代码分析
此代码实现了一个餐厅点餐系统。主要的类包括:菜品类(Dish)、菜谱类(Menu)、点菜记录类(Record)、订单类(Order)、时间类(Time)和餐厅类(Restaurant)。菜品类(Dish)保存了菜品的名称和单价信息,并提供了计算价格的方法。菜谱类(Menu)保存了餐厅的菜单信息,包括多道菜品。可以根据菜名查找菜品信息。点菜记录类(Record)保存了一道菜品的点餐记录,包括序号、菜品、份额和份数等信息。提供了计价方法。订单类(Order)保存了一个桌子的点餐记录,包括多个点菜记录。提供了计算订单总价、添加一条点菜记录、代点菜品和删除记录等方法。时间类(Time)保存了点餐的时间信息,能够计算当前是否在餐厅的营业时间内以及折扣。餐厅类(Restaurant)保存了多个桌子的订单信息。提供了添加桌子、查找桌子和获取餐厅订单信息等方法。主函数(Main)负责处理用户输入,并调用相关方法实现餐厅点餐系统的功能。在主函数中,首先通过Scanner类获取用户输入的信息,根据不同的输入执行相关操作,包括添加桌子、点菜、代点、删除记录和添加菜单等操作。最后遍历餐厅的订单信息,根据订单的运营时间计算总价并输出。
第五次题目集7-1菜单计价4:
import java.util.Scanner; import java.util.Calendar; import java.lang.Math; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Menu menu = new Menu();//菜单初始化 Restaurant restaurant = new Restaurant();//订单初始化 Order ordering = null; boolean endMenu = false; while(true) { String input = scanner.nextLine();//输入 if (input.equals("end")) { break; } String[] str = input.split(" "); if(Input_beginTable(input)&&!endMenu){endMenu = true;}//有餐桌信息输入结束菜单添加 if(!endMenu){ if(Input_menu(input)>0){//添加菜单 if(str.length == 3) menu.addDish(str[0], Integer.parseInt(str[1]), true); else menu.addDish(str[0], Integer.parseInt(str[1]), false); }else{ System.out.println("wrong format"); } }else{ if(Input_menu(input)>0 && ordering!=null){ System.out.println("invalid dish"); continue;//正在点菜就直接忽略 }else if(Input_menu(input)>0 && ordering==null){ continue; } } //table if(Input_beginTable(input)){ if(!str[0].equals("table")){ Pattern pattern = Pattern.compile("\\s"); String s = pattern.matcher(input).replaceAll(""); Pattern PTable = Pattern.compile("table"); if(PTable.matcher(s).find()){ System.out.println("wrong format"); continue; } }else if(Input_table(input)){//添加餐桌信息 if(Integer.parseInt(str[1])>55){//桌号超过55 System.out.println(Integer.parseInt(str[1]) + " table num out of range"); ordering = null; continue; } if(!restaurant.JudgeEffective(str[2], str[3])) {//日期时间错误 System.out.println(str[1]+" date error"); ordering = null; continue; } Time time = new Time(str[2], str[3]);//不在运营时间 if(!time.isValidPeriod()){ System.out.println("not a valid time period"); ordering = null; continue; } if(time.isChowtime() == 0){//不在运营时间 System.out.println("table " + Integer.parseInt(str[1]) + " out of opening hours"); ordering = null; continue; } ordering = new Order(Integer.parseInt(str[1]),time);//记录点单桌号 restaurant.addTable(ordering); System.out.println("table " + Integer.parseInt(str[1]) + ": "); continue; }else{ ordering = null; System.out.println("wrong format"); } } if(ordering == null){//没有添加餐桌信息则不执行添加订单等操作 continue; } if(Input_delete(input)) {//删除 ordering.delARecordByOrderNum(Integer.parseInt(str[0])); }else if(Input_record(input)) {//添加订单 ordering.addARecord( Integer.parseInt(str[0]), str[1], Integer.parseInt(str[2]), Integer.parseInt(str[3]), menu); }else if(Input_substitute(input)){//代点 if(restaurant.findTableByNum(Integer.parseInt(str[0]))==null||Integer.parseInt(str[0])==ordering.getTableNum()){//subTableNum不存在 System.out.println("Table number :" + Integer.parseInt(str[0]) + " does not exist"); continue; } ordering.substituteARecord( Integer.parseInt(str[0]), Integer.parseInt(str[1]), str[2], Integer.parseInt(str[3]), Integer.parseInt(str[4]), menu); }else { System.out.println("wrong format"); } }//while outPut(restaurant); } public static int Input_menu(String line){ if(line.matches("^[\u4e00-\u9fa5]+ \\d+ T$")){//特色菜 return 2; }else if(line.matches("^[\u4e00-\u9fa5]+ \\d+$")){//普通菜 return 1; }else{ return 0; } } public static boolean Input_beginTable(String line){ //包含“table”、日期、时间其中一个 Pattern pattern1 = Pattern.compile("table"); Pattern pattern2 = Pattern.compile("\\d{4}/\\d{1,2}/\\d{1,2}"); Pattern pattern3 = Pattern.compile("\\d{1,2}/\\d{1,2}/\\d{1,2}"); if(pattern1.matcher(line).find()||pattern2.matcher(line).find()||pattern3.matcher(line).find()){ return true; }else{ return false; } } public static boolean Input_table(String line){ if(line.matches("^table [1-9]\\d* \\d{4}/\\d{1,2}/\\d{1,2} \\d{1,2}/\\d{1,2}/\\d{1,2}$")){//餐桌信息 return true; }else { return false; } } public static boolean Input_record(String line){ if(line.matches("^[1-9]\\d* [\\u4e00-\\u9fa5]+ [1-9]\\d* [1-9]\\d*$")){//点菜 return true; }else { return false; } } public static boolean Input_substitute(String line){ if(line.matches("^[1-9]\\d* [1-9]\\d* [\u4e00-\u9fa5]+ [1-9]\\d* [1-9]\\d*$")){//帮点 return true; }else { return false; } } public static boolean Input_delete(String line){ if(line.matches("^[1-9]\\d* delete$")){//删除 return true; }else { return false; } } public static void outPut(Restaurant restaurant){ Restaurant tables = new Restaurant(); Order[] pay = tables.getRestaurant();//结算账单 Order[] array = restaurant.getRestaurant(); // 外层循环遍历每个元素 for (int i = 0; i < array.length; i++) { if(array[i]!=null){ //if(tables.findTableByNum(array[i].getTableNum())==null){ pay[i] = array[i]; //} // 内层循环与后面的元素进行比较 for (int j = i + 1; j < array.length; j++) { if(array[j]!=null){ if (restaurant.SameTimePeriod(array[i],array[j])) {//时间段相同 pay[i].consolidateOrder(array[j]);//合并订单 array[j] = null; } } } } } for(Order re : pay){ if(re!=null){ System.out.println("table " + re.getTableNum() + ": " + re.getOriginalPrice() + " " + re.getDiscountPrice());//总价 } } /* for(Order re : restaurant.getRestaurant()){ if(re!=null){ System.out.println("table " + re.getTableNum() + ": " + re.getOriginalPrice() + " " + re.getDiscountPrice());//总价 } }*/ } } //菜品类 class Dish { private String name;//菜品名称 private int unit_price; // 单价 private boolean specialty;//特色菜 public Dish(String name, int unitPrice, boolean specialty) {//记录dish this.name = name; this.unit_price = unitPrice; this.specialty = specialty; } public int getPrice(int portion){//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份) if (portion == 1) { // 小份 return unit_price; } else if (portion == 2) { // 中份 return (int) Math.round(unit_price * 1.5); } else if (portion == 3) { // 大份 return unit_price * 2; } else { return -1; // 非法份额 } } public void setUnit_price(int price) {//设置底价 this.unit_price = price; } public int getUnit_price() {//获得底价 return unit_price; } public String getName() {//获取菜名 return name; } public void setName(String name) {//设置菜名 this.name = name; } public void setSpecialty(int price) {//设置特色菜 this.specialty = specialty; } public boolean getSpecialty() {//获得特色菜 return specialty; } } //菜谱类 class Menu { private Dish[] dishs ;//菜品数组,保存所有菜品信息 private int i; public Menu() { this.dishs = new Dish[10]; this.i = 0; } public Dish searthDish(String dishName){//根据菜名在菜谱中查找菜品信息,返回Dish对象。 for(Dish dish : dishs) { if(dish!=null&&dish.getName().equals(dishName)) { return dish; } } return null; } public void addDish(String dishName,int unit_price,boolean specialty){//添加一道菜品信息 if(unit_price<=0||unit_price>=300){ System.out.println(dishName + " price out of range " + unit_price);//价格超出范围 return; } for (Dish dish : dishs) {//更改菜价 if(dish !=null && dish.getName().equals(dishName)){ dish.setUnit_price(unit_price); return; } } Dish dish = new Dish(dishName, unit_price, specialty); if (i < dishs.length) { dishs[i++] = dish; } //else {System.out.println("菜品已达到最大数量,无法继续添加。");} } } //点菜记录类 class Record { private int orderNum;//序号\ private Dish d;//菜品\ private int portion;//份额(1/2/3代表小/中/大份)\ private int num;//份数 private boolean delete;//删除标志 public Record(int orderNum, String dishName, int portion,int num,Menu menu) { this.orderNum = orderNum; this.portion = portion; this.num = num; this.d = menu.searthDish(dishName); this.delete = false; } public int getPrice(){//计价,计算本条记录的价格\ return num*d.getPrice(portion); } public int getOrderNum() { return orderNum; } public void setOrderNum(int orderNum) { this.orderNum = orderNum; } public boolean getDelete() { return delete; } public void setDelete(boolean delete) { this.delete = delete; } public Dish getDish() { return d; } public int getPortion() { return portion; } public void setPortion(int portion) { this.portion = portion; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } } //订单类 class Order { private Record[] records;//保存订单上每一道的记录 private int tableNum;//桌号 private Time time;//点餐时间 private int number;//菜数 public Order(int tableNum,Time time) { this.records = new Record[50]; this.tableNum=tableNum; this.time=time; this.number = 0; } public Record[] getRecord() { return records; } public int getDiscountPrice(){//计算订单的总价 int totalPrice = 0; for (Record record : records) { if (record != null&&!record.getDelete()) { totalPrice += (int)Math.round(record.getPrice()*time.getDiscount(record.getDish())/10.0); } } return totalPrice; } public int getOriginalPrice(){//计算订单的总价 int totalPrice = 0; for (Record record : records) { if (record != null&&!record.getDelete()) { totalPrice += record.getPrice(); } } return totalPrice;//四舍五入 } public void substituteARecord(int subTableNum, int orderNum,String dishName,int portion,int num,Menu menu){//代点一条菜品信息到订单中。 if (orderNum >= 0 && orderNum < records.length) { if(menu.searthDish(dishName) == null){ System.out.println(dishName + " does not exist");//菜单中没找到该菜 }else { Record record = new Record(orderNum, dishName, portion, num, menu); number++; records[number] = record; int totalPrice = record.getPrice(); System.out.println(orderNum + " table " + tableNum + " pay for table " + subTableNum + " " + totalPrice); } } // else {System.out.println("无法添加记录,序号超出范围。");} } public void addARecord(int orderNum,String dishName,int portion,int num,Menu menu){//添加一条菜品信息到订单中。 if (orderNum >= 0 && orderNum < records.length) { if(records[number]!=null && records[number].getOrderNum()>=orderNum){//序号小于或等于上一个菜 System.out.println("record serial number sequence error");//点菜序号错误 }else if(menu.searthDish(dishName) == null){ System.out.println(dishName + " does not exist");//菜单中没有 }else if(portion<1||portion>3){ System.out.println(orderNum + " portion out of range " + portion);//份额不为1、2、3 }else if(num>15) { System.out.println(orderNum + " num out of range " + num);//份数超过15 } else{ Record record = new Record(orderNum, dishName, portion, num, menu); records[++number] = record; int totalPrice = record.getPrice(); System.out.println(orderNum + " " + dishName + " " + totalPrice); } } // else {System.out.println("无法添加记录,序号超出范围。");} } public void consolidateOrder(Order order){//合并订单 for(Record record1 : order.getRecord()){ if(record1!=null){ if(findRecordByName(record1)==null){//无菜名、份额相同 records[++number] = record1; }else{ findRecordByName(record1).setNum(findRecordByName(record1).getNum()+record1.getNum());//份数相加 } } } } public void delARecordByOrderNum(int orderNum){//根据序号删除一条记录 if(findRecordByNum(orderNum)==null){ System.out.println("delete error;");//要删除的序号不存在 }else if(findRecordByNum(orderNum).getDelete()){ System.out.println("deduplication " + orderNum);//重复删除 }else{ findRecordByNum(orderNum).setDelete(true); } } public Record findRecordByNum(int orderNum){//根据序号查找一条记录 for (Record record : records) { if (record != null && record.getOrderNum() == orderNum) { return record; } } return null; } public Record findRecordByName(Record record){//根据菜名查找一条记录 for (Record re : records) { if (re != null && re.getDish().equals(record.getDish()) && re.getPortion() == record.getPortion()) { return re; } } return null; } public int getTableNum(){ return tableNum; } public void setTableNum(int tableNum){ this.tableNum=tableNum; } public Time getTime(){ return time; } public void setTime(Time time){ this.time=time; } } class Time{ private int year; private int month; private int day; private int hour; private int minute; private int seconds; public Time(String time1, String time2){ String[] str1 = time1.split("/"); String[] str2 = time2.split("/"); int year = Integer.parseInt(str1[0]); int month = Integer.parseInt(str1[1]); int day = Integer.parseInt(str1[2]); int hour = Integer.parseInt(str2[0]); int minute = Integer.parseInt(str2[1]); int seconds = Integer.parseInt(str2[2]); this.year=year; this.month=month; this.day=day; this.hour=hour; this.minute=minute; this.seconds=seconds; } public int getYear(){ return year; } public int getMonth(){ return month; } public int getDay(){ return day; } public int getHour(){ return hour; } public int getMinute(){ return minute; } public int getSeconds(){ return seconds; } public int getDiscount(Dish dish){//判断是否营业并返回折扣 Calendar time = Calendar.getInstance(); time.set(year, month-1, day, hour, minute, seconds); int weekDay = time.get(Calendar.DAY_OF_WEEK); int moment = hour*60*60+minute*60+seconds; if(weekDay>=2 && weekDay<=6){//周一到周五 if(moment>=61200 && moment<=73800){//17:00--20:30 if(dish.getSpecialty()){//特色菜七折 return 7; } return 8; }else if(moment>=37800 && moment<=52200){//10:30--14:30 if(dish.getSpecialty()){//特色菜七折 return 7; } return 6; }else { return 0; } }else{//周末 if(moment>=34200 && moment<=77400){//9:30--21:30 return 10; }else{ return 0; } } } public int isChowtime(){//判断是否营业 Calendar time = Calendar.getInstance(); time.set(year, month-1, day, hour, minute, seconds); int weekDay = time.get(Calendar.DAY_OF_WEEK); int moment = hour*60*60+minute*60+seconds; if(weekDay>=2 && weekDay<=6){//周一到周五 if(moment>=61200 && moment<=73800){//17:00--20:30 return 1; }else if(moment>=37800 && moment<=52200){//10:30--14:30 return 2; }else { return 0; } }else{ if(moment>=34200 && moment<=77400){//9:30--21:30 return 3; }else{ return 0; } } } public boolean isValidPeriod(){ Calendar startTime = Calendar.getInstance(); startTime.set(2022, 0, 1); Calendar endTime = Calendar.getInstance(); endTime.set(2023, 11, 31); Calendar time = Calendar.getInstance(); time.set(year, month-1, day); if(time.before(startTime)||time.after(endTime)){ return false; }else { return true; } } } class Restaurant{ private Order[] tables; private int number; public Restaurant(){ this.tables = new Order[56]; this.number = 0; } public void addTable(Order order) { tables[++number] = order; } public Order[] getRestaurant(){ return tables; } public Order findTableByNum(int tableNum){ for(Order order : tables){ if(order!=null&&order.getTableNum() == tableNum){ return order; } } return null; } public boolean SameTimePeriod(Order order1,Order order2){ Time time1 = order1.getTime(); Time time2 = order2.getTime(); if(time1.getYear()==time2.getYear()&&time1.getMonth()==time2.getMonth()&&time1.getDay()==time2.getDay()){ int t = time2.getHour()*60*60+time2.getMinute()*60+time2.getSeconds(); int T = time1.getHour()*60*60+time1.getMinute()*60+time1.getSeconds(); if(time1.isChowtime() == 3 && time2.isChowtime() == 3){ if(Math.abs(T-t)>=3600){ return true; } }else{ if((time1.isChowtime() == 1 && time2.isChowtime() == 1)||(time1.isChowtime() == 2 && time2.isChowtime() == 2)){ return true; } } } return false; } public boolean JudgeEffective (String line1, String line2) { boolean count = false; if(line1.matches("^\\d{4}/([1-9]|0[1-9]|1[012])/([1-9]|0[1-9]|[12][0-9]|3[01])$")) {//日期判断 String[] data = line1.split("/"); int year = Integer.parseInt(data[0]); //转换为int型 int mouth = Integer.parseInt(data[1]); int day = Integer.parseInt(data[2]); if(mouth<1||mouth>12) { count=false; } else if(mouth==1||mouth==3||mouth==5||mouth==7||mouth==8||mouth==10||mouth==12) { if(day<=31) { count = true; } }//大月 else if(mouth==2) { if(year%400==0||(year%4==0&&year%100!=0)) { if(day<=29) {//闰年 count=true; } } else { if(day<=28) { count=true; } } }//二月 else { if(day<=30) { count = true; } }//小月 }//日期判断 if(!line2.matches("^([0-9]|1[0-9]|2[01234])/([0-9]|[0-5]\\d)/([0-9]|[0-5]\\d)$")){//时间判断 count = false; } return count; } }
该代码是一个餐厅点菜管理系统,实现了以下功能:
菜品添加与查询:通过Menu类和Dish类来实现,用户可以向Menu中添加新的菜品和价格信息,同时可以根据菜名进行查询。订单管理:通过Order类、Record类以及餐厅类Restaurant来实现。用户可以创建订单,向订单中添加新的点菜记录,删除记录,以及查找记录等功能。折扣计算:根据点菜的时间(Time类)、菜品种类和特色来进行折扣计算。这里主要根据餐厅的营业时间进行判断,不同时间段的折扣不同。订单合并与检查:餐厅中可以合并相同时间段的订单,对符合条件的订单进行合并。输入解析:用户在控制台输入命令,程序根据用户输入执行相应功能。如添加菜品、点菜、删除记录、代点、结算等操作。输出:程序运行结束后,输出所有餐桌的原价(不打折)和折后价。
代码中主要包含以下类:
Dish: 菜品类,包含菜品名称、价格和特色信息。Menu: 菜谱类,包含Dish数组,用于存储所有菜品信息,并提供添加和查询功能。Record: 点菜记录类,记录订单中的菜品信息,如菜品、份数和删除标志。Order: 订单类,包含Record数组,用于存储一个订单的所有点菜记录,并提供添加、删除、查询和合并功能。Time: 时间类,包含年、月、日、时、分、秒等信息,用于计算折扣。Restaurant: 餐厅类,包含Order数组,用于存储所有订单,并提供查询、合并、检查等功能。
代码运行流程如下:
用户在控制台输入信息,程序通过解析输入来执行相应操作。用户可添加菜品,点菜、删除记录、代点等操作,并将结果实时输出到控制台。当输入结束后,程序计算所有餐桌的原价和折后价,并输出到控制台。
第六次题目集7-1菜单计价5:
import java.sql.SQLOutput; import java.util.Scanner; import java.util.Calendar; import java.lang.Math; import java.util.regex.Pattern; import java.util.Arrays; import java.util.Comparator; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Menu menu = new Menu();//菜单初始化 Restaurant restaurant = new Restaurant();//订单初始化 Order ordering = null; boolean endMenu = false; while(true) { String input = scanner.nextLine();//输入 if (input.equals("end")) { break; } String[] str = input.split(" "); if(Input_beginTable(input)&&!endMenu){endMenu = true;}//有餐桌信息输入结束菜单添加 if(!endMenu){ if(Input_menu(input)==2){ menu.addDish(str[0], str[1], Integer.parseInt(str[2]), true); } else if(Input_menu(input)==1){ menu.addDish(str[0], null, Integer.parseInt(str[1]), false); }else{ System.out.println("wrong format"); } }else{ if(Input_menu(input)>0 && ordering!=null){ System.out.println("invalid dish"); continue;//正在点菜就直接忽略 }else if(Input_menu(input)>0 && ordering==null){ continue; } } //table if(Input_beginTable(input)){ if(!str[0].equals("table")){ Pattern pattern = Pattern.compile("\\s"); String s = pattern.matcher(input).replaceAll(""); Pattern PTable = Pattern.compile("table"); if(PTable.matcher(s).find()){ System.out.println("wrong format"); continue; } }else if(Input_table(input)){//添加餐桌信息 if(Integer.parseInt(str[1])>55){//桌号超过55 System.out.println(Integer.parseInt(str[1]) + " table num out of range"); ordering = null; continue; } if(!restaurant.JudgeEffective(str[5], str[6])) {//日期时间错误 System.out.println(str[1]+" date error"); ordering = null; continue; } Time time = new Time(str[5], str[6]);//不在运营时间 if(!time.isValidPeriod()){ System.out.println("not a valid time period"); ordering = null; continue; } if(time.isChowtime() == 0){//不在运营时间 System.out.println("table " + Integer.parseInt(str[1]) + " out of opening hours"); ordering = null; continue; } ordering = new Order(Integer.parseInt(str[1]),str[3], str[4],time);//记录点单桌号信息 restaurant.addTable(ordering); System.out.println("table " + Integer.parseInt(str[1]) + ": "); continue; }else{ ordering = null; System.out.println("wrong format"); } } if(ordering == null){//没有添加餐桌信息则不执行添加订单等操作 continue; } if(Input_delete(input)) {//删除 ordering.delARecordByOrderNum(Integer.parseInt(str[0])); }else if(Input_record(input)>0) {//添加订单 if(Input_record(input)==1){//普通菜 ordering.addARecord(Integer.parseInt(str[0]), str[1],-1, Integer.parseInt(str[2]), Integer.parseInt(str[3]), menu); }else if(Input_record(input)==2){//特色菜 ordering.addARecord(Integer.parseInt(str[0]), str[1], Integer.parseInt(str[2]), Integer.parseInt(str[3]), Integer.parseInt(str[4]), menu); } }else if(Input_substitute(input)>0){//代点 if(restaurant.findTableByNum(Integer.parseInt(str[0]))==null||Integer.parseInt(str[0])==ordering.getTableNum()){//subTableNum不存在 System.out.println("Table number :" + Integer.parseInt(str[0]) + " does not exist"); continue; } if(Input_substitute(input)==1){//普通菜 ordering.substituteARecord(Integer.parseInt(str[0]), Integer.parseInt(str[1]), str[2], -1, Integer.parseInt(str[3]), Integer.parseInt(str[4]), menu, restaurant); }else if(Input_substitute(input)==2){ ordering.substituteARecord(Integer.parseInt(str[0]), Integer.parseInt(str[1]), str[2], Integer.parseInt(str[3]), Integer.parseInt(str[4]), Integer.parseInt(str[5]), menu, restaurant); } }else { System.out.println("wrong format"); } }//while outPut(restaurant);//最终输出 } public static int Input_menu(String line){ if(line.matches("^[\u4e00-\u9fa5]+ [\u4e00-\u9fa5]+ \\d+ T$")){//特色菜 return 2; }else if(line.matches("^[\u4e00-\u9fa5]+ \\d+$")){//普通菜 return 1; }else{ return 0; } } public static boolean Input_beginTable(String line){ //包含“table”、日期、时间其中一个 Pattern pattern1 = Pattern.compile("table"); Pattern pattern2 = Pattern.compile("\\d{4}/\\d{1,2}/\\d{1,2}"); Pattern pattern3 = Pattern.compile("\\d{1,2}/\\d{1,2}/\\d{1,2}"); Pattern pattern5 = Pattern.compile("(180|181|189|133|135|136)\\d{8}"); if(pattern1.matcher(line).find() ||pattern2.matcher(line).find() ||pattern3.matcher(line).find() ||pattern5.matcher(line).find()){ return true; }else{ return false; } } public static boolean Input_table(String line){ if(line.matches("^table [1-9]\\d* : [A-Za-z]{1,10} (180|181|189|133|135|136)\\d{8} \\d{4}/\\d{1,2}/\\d{1,2} \\d{1,2}/\\d{1,2}/\\d{1,2}$")){//餐桌信息 return true; }else { return false; } } public static int Input_record(String line){ if(line.matches("^[1-9]\\d* [\\u4e00-\\u9fa5]+ \\d* [1-9]\\d* [1-9]\\d*$")){//点特色菜 return 2; }else if(line.matches("^[1-9]\\d* [\\u4e00-\\u9fa5]+ [1-9]\\d* [1-9]\\d*$")){//点菜 return 1; }else { return 0; } } public static int Input_substitute(String line){ if(line.matches("^[1-9]\\d* [1-9]\\d* [\u4e00-\u9fa5]+ \\d* [1-9]\\d* [1-9]\\d*$")){ return 2; }else if(line.matches("^[1-9]\\d* [1-9]\\d* [\u4e00-\u9fa5]+ [1-9]\\d* [1-9]\\d*$")){//帮点 return 1; }else { return 0; } } public static boolean Input_delete(String line){ if(line.matches("^[1-9]\\d* delete$")){//删除 return true; }else { return false; } } public static void outPut(Restaurant restaurant){ //川菜增加辣度值:辣度0-5级;对应辣度水平为:不辣、微辣、稍辣、辣、很辣、爆辣; //晋菜增加酸度值,酸度0-4级;对应酸度水平为:不酸、微酸、稍酸、酸、很酸; //浙菜增加甜度值,甜度0-3级;对应酸度水平为:不甜、微甜、稍甜、甜; String[] spicy = {"不辣","微辣","稍辣","辣","很辣","爆辣"}; String[] sour = {"不酸","微酸","稍酸","酸","很酸"}; String[] sweet = {"不甜","微甜","稍甜","甜"}; // tables = new Restaurant(); Order[] pay = restaurant.getRestaurant();//结算账单 //Order[] array = restaurant.getRestaurant(); Payment[] payments = new Payment[56]; int count=0; /* // 外层循环遍历每个元素 for (int i = 0; i < array.length; i++) { if(array[i]!=null){ pay[i] = array[i]; for (int j = i + 1; j < array.length; j++) {//遍历该元素后面是否有相同数据 if(array[j]!=null){ if (restaurant.SameTimePeriod(array[i],array[j])) {//时间段相同 pay[i].consolidateOrder(array[j]);//合并订单 array[j] = null; } } } } }*/ for(Order re : pay){ if(re!=null){ payments[count++] = new Payment(re.getCustomer(), re.getPhone(),re.getDiscountPrice()); System.out.print("table "+re.getTableNum()+": "+re.getOriginalPrice()+" "+re.getDiscountPrice());//总价 if(re.getSpicy()>=0){ System.out.print(" 川菜 "+ re.getSpicyNum() +" "+spicy[re.getSpicy()]); } if(re.getSour()>=0){ System.out.print(" 晋菜 "+ re.getSourNum() +" "+sour[re.getSour()]); } if(re.getSweet()>=0){ System.out.print(" 浙菜 "+ re.getSweetNum() +" "+sweet[re.getSweet()]); } if(re.getSpicy()<0&&re.getSour()<0&&re.getSweet()<0){ System.out.println(" ");//换行 }else{ System.out.println();//换行 } } } Payment[] finalPay = consolidatePayment(payments); for(Payment p : finalPay){ System.out.println(p.getName()+" "+p.getPhone()+" "+p.getMoney()); } } public static Payment[] consolidatePayment(Payment[] payments){ Payment[] pay = new Payment[56]; for (int i = 0; i < payments.length; i++) { if(payments[i]!=null){ pay[i] = new Payment(payments[i].getName(),payments[i].getPhone(),payments[i].getMoney()); for (int j = i + 1; j < payments.length; j++) {//遍历该元素后面是否有相同数据 if(payments[j]!=null){ if (pay[i].getName().equals(payments[j].getName())) {//时间段相同 pay[i].setMoney(pay[i].getMoney()+payments[j].getMoney()); payments[j] = null; } } } } } Payment[] finalPay = Arrays.stream(pay) .filter(p -> p != null) .toArray(Payment[]::new); Arrays.sort(finalPay, Comparator.comparing(Payment::getName));//按字母顺序排序 return finalPay; } } class Payment{//支付 private String name; private String phone; private int money; public Payment(String name,String phone,int money){ this.name = name; this.phone = phone; this.money = money; } public String getName(){ return name; } public String getPhone(){ return phone; } public int getMoney(){ return money; } public void setMoney(int money){ this.money = money; } } //菜品类 class Dish { private String name;//菜品名称 private String type;//菜品类型 private int unit_price; // 单价 private boolean specialty;//特色菜 private int degree;//程度 public Dish(String name, String type, int unitPrice, boolean specialty) {//记录dish this.name = name; this.type = type; this.unit_price = unitPrice; this.specialty = specialty; this.degree = -1; } public Dish(String name, int unitPrice, boolean specialty) {//记录dish this.name = name; this.unit_price = unitPrice; this.specialty = specialty; } public int getPrice(int portion){//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份) if (portion == 1) { // 小份 return unit_price; } else if (portion == 2) { // 中份 return (int) Math.round(unit_price * 1.5); } else if (portion == 3) { // 大份 return unit_price * 2; } else { return -1; // 非法份额 } } public void setType(String type) {//设置菜品类型 this.type = type; } public String getType() {//获得菜品类型 return type; } public void setDegree(int degree) {//设置程度 this.degree = degree; } public int getDegree() {//获得程度 return degree; } public void setUnit_price(int price) {//设置底价 this.unit_price = price; } public int getUnit_price() {//获得底价 return unit_price; } public String getName() {//获取菜名 return name; } public void setName(String name) {//设置菜名 this.name = name; } public void setSpecialty(boolean specialty) {//设置特色菜 this.specialty = specialty; } public boolean getSpecialty() {//获得特色菜 return specialty; } } //菜谱类 class Menu { private Dish[] dishs ;//菜品数组,保存所有菜品信息 private int i; public Menu() { this.dishs = new Dish[10]; this.i = 0; } public Dish searthDish(String dishName){//根据菜名在菜谱中查找菜品信息,返回Dish对象。 for(Dish dish : dishs) { if(dish!=null&&dish.getName().equals(dishName)) { return dish; } } return null; } public void addDish(String dishName, String type, int unit_price,boolean specialty){//添加一道菜品信息 if((unit_price <= 0) || (unit_price >= 300)){ System.out.println(dishName + " price out of range " + unit_price);//价格超出范围 return; } for (Dish dish : dishs) {//更改菜价 if(dish !=null && dish.getName().equals(dishName)){ dish.setUnit_price(unit_price); return; } } Dish dish = new Dish(dishName, type, unit_price, specialty); if (i < dishs.length) { dishs[i++] = dish; } //else {System.out.println("菜品已达到最大数量,无法继续添加。");} } } //点菜记录类 class Record { private int orderNum;//序号\ private Dish d;//菜品\ private int portion;//份额(1/2/3代表小/中/大份)\ private int num;//份数 private boolean delete;//删除标志 public Record(int orderNum, String dishName, int degree, int portion,int num,Menu menu) { this.orderNum = orderNum; this.portion = portion; this.num = num; this.d = menu.searthDish(dishName); this.d = new Dish(menu.searthDish(dishName).getName(), menu.searthDish(dishName).getType(), menu.searthDish(dishName).getUnit_price(), menu.searthDish(dishName).getSpecialty()); d.setDegree(degree); this.delete = false; } public boolean degreeOver(){ if(!d.getSpecialty()){ return false; } if(d.getType().equals("川菜")&&d.getDegree()>5){ System.out.println("spicy num out of range :"+d.getDegree()); return true; }else if(d.getType().equals("晋菜")&&d.getDegree()>4){ System.out.println("acidity num out of range :"+d.getDegree()); return true; }else if(d.getType().equals("浙菜")&&d.getDegree()>3){ System.out.println("sweetness num out of range :"+d.getDegree()); return true; } return false; } public int getPrice(){//计价,计算本条记录的价格\ return num*d.getPrice(portion); } public int getOrderNum() { return orderNum; } public void setOrderNum(int orderNum) { this.orderNum = orderNum; } public boolean getDelete() { return delete; } public void setDelete(boolean delete) { this.delete = delete; } public Dish getDish() { return d; } public int getPortion() { return portion; } public void setPortion(int portion) { this.portion = portion; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } } //订单类 class Order { private Record[] records;//保存订单上每一道的记录 private int tableNum;//桌号 private Time time;//点餐时间 private int number;//菜数 private String customer; private String phone; public Order(int tableNum,String customer,String phone,Time time) { this.records = new Record[50]; this.tableNum = tableNum; this.customer = customer; this.phone = phone; this.time = time; this.number = 0; } public Record[] getRecord() { return records; } public int getDiscountPrice(){//计算订单的总价 int totalPrice = 0; for (Record record : records) { if (record != null&&!record.getDelete()) { totalPrice += (int)Math.round(record.getPrice()*time.getDiscount(record.getDish())/10.0); } } return totalPrice; } public int getOriginalPrice(){//计算订单的总价 int totalPrice = 0; for (Record record : records) { if (record != null&&!record.getDelete()) { totalPrice += record.getPrice(); } } return totalPrice;//四舍五入 } public void substituteARecord(int subTableNum, int orderNum,String dishName,int degree,int portion,int num,Menu menu,Restaurant restaurant){//代点一条菜品信息到订单中。 if (orderNum >= 0 && orderNum < records.length) { if(menu.searthDish(dishName) == null){ System.out.println(dishName + " does not exist");//菜单中没找到该菜 }else { Record record1 = new Record(orderNum, dishName,degree, portion, num, menu); record1.getDish().setUnit_price(0);//一个不用付钱的菜 Order order1 = restaurant.findTableByNum(subTableNum); order1.setNumber(order1.getNumber()+1); order1.getRecord()[order1.getNumber()] = record1;//subTable Record record2 = new Record(orderNum, dishName,degree, portion, num, menu); record2.getDish().setDegree(-1); record2.getDish().setType(null);//只算钱 records[++number] = record2; int totalPrice = record2.getPrice(); System.out.println(orderNum + " table " + tableNum + " pay for table " + subTableNum + " " + totalPrice); } } // else {System.out.println("无法添加记录,序号超出范围。");} } public void addARecord(int orderNum,String dishName,int degree,int portion,int num,Menu menu){//添加一条菜品信息到订单中。 if (orderNum >= 0 && orderNum < records.length) { if(menu.searthDish(dishName) == null){ System.out.println(dishName + " does not exist");//菜单中没有 return; } Record record; record = new Record(orderNum, dishName, degree, portion, num, menu); if(portion<1||portion>3){ System.out.println(orderNum + " portion out of range " + portion);//份额不为1、2、3 }else if(num>15) { System.out.println(orderNum + " num out of range " + num);//份数超过15 }else if(record.degreeOver()) { //在判断中已经处理 }else { records[++number] = record; int totalPrice = record.getPrice(); System.out.println(orderNum + " " + dishName + " " + totalPrice); } } // else {System.out.println("无法添加记录,序号超出范围。");} } public void consolidateOrder(Order order){//合并订单 for(Record record1 : order.getRecord()){ if(record1!=null){ if(findRecordByName(record1)==null){//无菜名、份额相同 records[++number] = record1; }else{ findRecordByName(record1).setNum(findRecordByName(record1).getNum()+record1.getNum());//份数相加 } } } } public void delARecordByOrderNum(int orderNum){//根据序号删除一条记录 if(findRecordByNum(orderNum)==null){ System.out.println("delete error;");//要删除的序号不存在 }else if(findRecordByNum(orderNum).getDelete()){ System.out.println("deduplication " + orderNum);//重复删除 }else{ findRecordByNum(orderNum).setDelete(true); } } public Record findRecordByNum(int orderNum){//根据序号查找一条记录 for (Record record : records) { if (record != null && record.getOrderNum() == orderNum) { return record; } } return null; } public Record findRecordByName(Record record){//根据菜名查找一条记录 for (Record re : records) { if (re != null && re.getDish().equals(record.getDish()) && re.getPortion() == record.getPortion()) { return re; } } return null; } public int getSpicy(){//平均辣度 int count = 0; int total = 0; for(Record re : records){ if(re != null && re.getDish().getType()!=null&& re.getDish().getType().equals("川菜")&&!re.getDelete()){ count += re.getNum(); total += re.getDish().getDegree()*re.getNum(); } } if(count == 0){ return -1; } return (int) Math.round((double) total /count); } public int getSpicyNum(){ int count = 0; for(Record re : records){ if(re != null && re.getDish().getType()!=null&& re.getDish().getType().equals("川菜")&&!re.getDelete()){ count += re.getNum(); } } return count; } public int getSour(){//平均酸度 int count = 0; int total = 0; for(Record re : records){ if(re != null && re.getDish().getType()!=null && re.getDish().getType().equals("晋菜")&&!re.getDelete()){ count += re.getNum(); total += re.getDish().getDegree()*re.getNum(); } } if(count == 0){ return -1; } return (int) Math.round((double) total /count); } public int getSourNum(){ int count = 0; for(Record re : records){ if(re != null && re.getDish().getType()!=null&& re.getDish().getType().equals("晋菜")&&!re.getDelete()){ count += re.getNum(); } } return count; } public int getSweet(){//平均酸度 int count = 0; int total = 0; for(Record re : records){ if(re != null && re.getDish().getType()!=null && re.getDish().getType().equals("浙菜")&&!re.getDelete()){ count += re.getNum(); total += re.getDish().getDegree()*re.getNum(); } } if(count == 0){ return -1; } return (int) Math.round((double) total /count); } public int getSweetNum(){ int count = 0; for(Record re : records){ if(re != null && re.getDish().getType()!=null&& re.getDish().getType().equals("浙菜")&&!re.getDelete()){ count += re.getNum(); } } return count; } public int getNumber(){ return number; } public void setNumber(int number){ this.number=number; } public int getTableNum(){ return tableNum; } public void setTableNum(int tableNum){ this.tableNum=tableNum; } public Time getTime(){ return time; } public void setTime(Time time){ this.time=time; } public String getCustomer(){ return customer; } public void setCustomer(String customer){ this.customer=customer; } public String getPhone(){ return phone; } public void setPhone(String phone){ this.phone=phone; } } class Time{ private int year; private int month; private int day; private int hour; private int minute; private int seconds; public Time(String time1, String time2){ String[] str1 = time1.split("/"); String[] str2 = time2.split("/"); int year = Integer.parseInt(str1[0]); int month = Integer.parseInt(str1[1]); int day = Integer.parseInt(str1[2]); int hour = Integer.parseInt(str2[0]); int minute = Integer.parseInt(str2[1]); int seconds = Integer.parseInt(str2[2]); this.year=year; this.month=month; this.day=day; this.hour=hour; this.minute=minute; this.seconds=seconds; } public int getYear(){ return year; } public int getMonth(){ return month; } public int getDay(){ return day; } public int getHour(){ return hour; } public int getMinute(){ return minute; } public int getSeconds(){ return seconds; } public int getDiscount(Dish dish){//判断是否营业并返回折扣 Calendar time = Calendar.getInstance(); time.set(year, month-1, day, hour, minute, seconds); int weekDay = time.get(Calendar.DAY_OF_WEEK); int moment = hour*60*60+minute*60+seconds; if(weekDay>=2 && weekDay<=6){//周一到周五 if(moment>=61200 && moment<=73800){//17:00--20:30 if(dish.getSpecialty()){//特色菜七折 return 7; } return 8; }else if(moment>=37800 && moment<=52200){//10:30--14:30 if(dish.getSpecialty()){//特色菜七折 return 7; } return 6; }else { return 0; } }else{//周末 if(moment>=34200 && moment<=77400){//9:30--21:30 return 10; }else{ return 0; } } } public int isChowtime(){//判断是否营业 Calendar time = Calendar.getInstance(); time.set(year, month-1, day, hour, minute, seconds); int weekDay = time.get(Calendar.DAY_OF_WEEK); int moment = hour*60*60+minute*60+seconds; if(weekDay>=2 && weekDay<=6){//周一到周五 if(moment>=61200 && moment<=73800){//17:00--20:30 return 1; }else if(moment>=37800 && moment<=52200){//10:30--14:30 return 2; }else { return 0; } }else{ if(moment>=34200 && moment<=77400){//9:30--21:30 return 3; }else{ return 0; } } } public boolean isValidPeriod(){ Calendar startTime = Calendar.getInstance(); startTime.set(2022, 0, 1); Calendar endTime = Calendar.getInstance(); endTime.set(2023, 11, 31); Calendar time = Calendar.getInstance(); time.set(year, month-1, day); if(time.before(startTime)||time.after(endTime)){ return false; }else { return true; } } } class Restaurant{ private Order[] tables; private int number; public Restaurant(){ this.tables = new Order[56]; this.number = 0; } public void addTable(Order order) { tables[++number] = order; } public Order[] getRestaurant(){ return tables; } public Order findTableByNum(int tableNum){ for(Order order : tables){ if(order!=null&&order.getTableNum() == tableNum){ return order; } } return null; } public boolean SameTimePeriod(Order order1,Order order2){ Time time1 = order1.getTime(); Time time2 = order2.getTime(); if(time1.getYear()==time2.getYear()&&time1.getMonth()==time2.getMonth()&&time1.getDay()==time2.getDay()){ int t = time2.getHour()*60*60+time2.getMinute()*60+time2.getSeconds(); int T = time1.getHour()*60*60+time1.getMinute()*60+time1.getSeconds(); if(time1.isChowtime() == 3 && time2.isChowtime() == 3){ if(Math.abs(T-t)>=3600){ return true; } }else{ if((time1.isChowtime() == 1 && time2.isChowtime() == 1)||(time1.isChowtime() == 2 && time2.isChowtime() == 2)){ return true; } } } return false; } public boolean JudgeEffective (String line1, String line2) {//时间有效 boolean count = false; if(line1.matches("^\\d{4}/([1-9]|0[1-9]|1[012])/([1-9]|0[1-9]|[12][0-9]|3[01])$")) {//日期判断 String[] data = line1.split("/"); int year = Integer.parseInt(data[0]); //转换为int型 int mouth = Integer.parseInt(data[1]); int day = Integer.parseInt(data[2]); if(mouth<1||mouth>12) { count=false; } else if(mouth==1||mouth==3||mouth==5||mouth==7||mouth==8||mouth==10||mouth==12) { if(day<=31) { count = true; } }//大月 else if(mouth==2) { if(year%400==0||(year%4==0&&year%100!=0)) { if(day<=29) {//闰年 count=true; } } else { if(day<=28) { count=true; } } }//二月 else { if(day<=30) { count = true; } }//小月 }//日期判断 if(!line2.matches("^([0-9]|1[0-9]|2[01234])/([0-9]|[0-5]\\d)/([0-9]|[0-5]\\d)$")){//时间判断 count = false; } return count; } }
这是一个餐厅管理系统的代码,主要用于处理餐厅的菜单、订单、支付等信息。
主要类和方法如下:
类Dish:菜品类,包含属性名称、类型、单价、特色菜和程度。提供计算菜品价格的方法。类Menu:菜谱类,包含一个Dish类型的数组,用于保存所有菜品信息。提供查找和添加菜品的方法。类Record:点菜记录类,包含订单号、菜品、份额、数量等属性。提供计算订单的价格的方法。类Order:订单类,包含一个Record类型的数组,保存每个订单的记录。提供添加、删除、查找记录的方法,计算订单总价等。类Time:时间类,包含年、月、日、时、分、秒属性。提供判断时间是否有效、是否在营业、折扣等方法。类Restaurant:餐厅类,包含一个Order类型的数组,保存所有桌子的订单信息。提供添加表、查找表和判断时间有效的方法。类Payment:支付类,包含客户名、电话和费用等属性。
代码运行过程:
初始化Scanner用于读取输入,并创建Menu和Restaurant实例。通过循环来不断读取输入的信息,并进行相应处理。对输入的内容进行相应处理,分别处理输入的菜单、订单、支付等信息。最终输出结果,包括每桌的订单情况和客户的支付信息。
期中考试:
7-1通过定义一个属性为圆的半径r,再用方法getArea()返回圆的面积,7-2 通过定义矩形对角两个点的坐标,然后通过坐标相减得到矩形的长和宽,再用方法getArea()返回长*宽
7-3继承和多态
import java.util.Scanner; import java.lang.Math; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); int choice = input.nextInt(); switch(choice) { case 1://Circle double radiums = input.nextDouble(); if(radiums<=0){ System.out.println("Wrong Format"); break; } Shape circle = new Circle(radiums); 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; } } private static void printArea(Shape shape) { System.out.printf("%.2f",shape.getArea()); } } class Shape{ public Shape(){ } public double getArea(){ return 0; } } class Circle extends Shape{ private double r; public Circle(double r){ this.r = r; } public double getArea(){ return Math.PI*r*r; } } class Rectangle extends Shape{ private Point topLeftPoint; private Point lowerRightPoint; public Rectangle(Point topLeftPoint,Point lowerRightPoint){ this.lowerRightPoint= lowerRightPoint; this.topLeftPoint = topLeftPoint; } public double getLength(){ return Math.abs(topLeftPoint.getX()-lowerRightPoint.getX()); } public double getHeight(){ return Math.abs(topLeftPoint.getY()-lowerRightPoint.getY()); } public double getArea(){ return getHeight()*getLength(); } public Point getLowerRightPoint() { return lowerRightPoint; } public void setLowerRightPoint(Point lowerRightPoint) { this.lowerRightPoint = lowerRightPoint; } public Point getTopLeftPoint() { return topLeftPoint; } public void setTopLeftPoint(Point topLeftPoint) { this.topLeftPoint = topLeftPoint; } } 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 void setX(double x){ this.x = x; } public double getY(){ return y; } public void setY(double y){ this.y = y; } }
将测验1与测验2的类设计进行合并设计,抽象出Shape父类(抽象类),Circle及Rectangle作为子类,其中,将printArea(Shape shape)方法定义为在Main类中的静态方法,通过调用父类中的getArea()方法,从而从子类getArea()方法中获取返回值,体现程序设计的多态性。
7-4抽象类和接口
import java.util.Scanner; import java.lang.Math; import java.util.ArrayList; import java.util.Comparator; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); ArrayList<Shape> list = new ArrayList<>(); int choice = input.nextInt(); while(choice != 0) { switch(choice) { case 1://Circle double radiums = input.nextDouble(); Shape circle = new Circle(radiums); 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()) + " "); } } } class Shape implements Comparable<Shape>{ public Shape(){ } public double getArea(){ return 0; } public int compareTo(Shape other){ Double area1 = this.getArea(); Double area2 = other.getArea(); return area1.compareTo(area2); } } class Circle extends Shape{ private double r; public Circle(double r){ this.r = r; } public double getArea(){ return Math.PI*r*r; } } class Rectangle extends Shape{ private Point topLeftPoint; private Point lowerRightPoint; public Rectangle(Point topLeftPoint,Point lowerRightPoint){ this.lowerRightPoint= lowerRightPoint; this.topLeftPoint = topLeftPoint; } public double getLength(){ return Math.abs(topLeftPoint.getX()-lowerRightPoint.getX()); } public double getHeight(){ return Math.abs(topLeftPoint.getY()-lowerRightPoint.getY()); } public double getArea(){ return getHeight()*getLength(); } public Point getLowerRightPoint() { return lowerRightPoint; } public void setLowerRightPoint(Point lowerRightPoint) { this.lowerRightPoint = lowerRightPoint; } public Point getTopLeftPoint() { return topLeftPoint; } public void setTopLeftPoint(Point topLeftPoint) { this.topLeftPoint = topLeftPoint; } } 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 void setX(double x){ this.x = x; } public double getY(){ return y; } public void setY(double y){ this.y = y; } }
在主函数中,先创建一个ArrayList对象list来存储用户输入的图形,然后使用一个循环读取用户输入的图形类型和参数,并根据图形类型创建对应的对象,添加到list中。最后,使用Comparator.naturalOrder方法对list中的图形对象进行排序,然后依次输出每个图形对象的面积。
三、踩坑心得
第四次题目集
7-1:合理规划类的属性和方法:在设计订单和菜单的类时,需要合理规划类的属性和方法。例如,订单类可以包含桌号、订单时间和订单记录等属性,可以包含计算总价的方法;菜单类可以包含菜品名称和价格等属性。
优化用户输入判断:用户输入的命令和数据可能存在不合法的情况,如桌号为空、菜单项名称为空等。需要在代码中进行输入判断,避免发生异常情况。
第五次题目集
7-1:
数据结构选择:在设计和实现类时,需要合理选择适当的数据结构来存储和组织数据。不同的数据结构适用于不同的场景,例如使用列表、数组、字典等。
类的设计:在设计类时,需考虑清楚类的属性和方法,彼此之间的关系和依赖,以及如何封装数据和行为。
错误处理和异常处理:编写代码时,需要考虑可能发生的错误和异常情况,并编写相应的错误处理和异常处理逻辑,以保证程序的稳定性和健壮性。
第六次题目集
7-1:
对用户输入进行严格验证。在用户输入菜单选项和数量时,要判断输入是否合法。如果用户输入了不存在的菜单选项或者数量小于等于0,需要进行相应的错误处理。
合理使用循环和条件语句。用户可以连续点餐或者多次修改订单,因此需要使用循环来处理多次输入。同时,需要根据用户的选择执行不同的操作,因此需要使用条件语句来实现分支逻辑。
主要困难
用户输入处理的复杂性:对于菜单选项和数量的输入,需要考虑各种不同的情况,如输入非数字字符、输入超出范围的数字等。处理这些复杂的用户输入可能会增加代码的复杂性和难度。
订单记录的管理和更新:在第二道题目中,需要对订单记录进行添加、修改、删除等操作。管理和更新订单记录时需要考虑多个条件的组合,如菜单选项和数量一致性、是否存在符合条件的订单等。处理这些逻辑可能会比较复杂。
错误处理和异常处理:在处理用户输入和订单记录时,可能会遇到各种错误和异常情况,如输入错误、文件读写失败等。处理这些错误和异常情况需要编写相应的错误处理和异常捕获逻辑,可能需要充分的测试和调试。
改进意见
合理使用函数和模块化编程:将不同功能的代码封装成函数,提高代码的可读性和复用性。例如,可以编写一个函数来处理用户输入,一个函数来管理订单记录,一个函数来实现菜单的显示和选择等。通过模块化编程,可以将复杂的逻辑分解成更小的任务,更容易管理和调试。
使用适当的数据结构:为了方便管理订单记录和菜单选项,可以选择合适的数据结构。例如,可以使用字典来存储订单记录,将菜单选项作为键,数量作为值。在管理订单记录时可以轻松进行添加、修改和删除操作。使用列表或集合来存储唯一的菜单项,以确保数据的一致性和唯一性。
编写严谨的输入验证和错误处理逻辑:在处理用户输入时,要进行严格的输入验证,避免出现不合法的输入。可以编写函数来验证菜单选项和数量的输入是否合法,并在出现错误时进行错误处理。同时,要预先考虑可能出现的错误和异常情况,编写相应的错误处理和异常捕获逻辑,以保证程序的稳定性和可靠性。
使用合适的数据结构来管理菜单选项和订单记录。例如使用列表来存储菜单选项,使用字典来存储订单记录。这样可以方便地进行增删改查等操作,节省编写逻辑代码的复杂度。
在编写完成后进行测试和调试。编写完代码后,要进行充分的测试和调试,以保证程序的正确性和稳定性。可以用不同的输入情况测试各种功能,同时注意捕获并处理可能出现的错误和异常情况。通过测试和调试,可以及时发现和修复问题,提高代码的质量。
五、总结
功能实现:这三个作业都是围绕订单管理系统展开的,从不同的角度实现了不同的功能。第一次作业主要是实现订单的添加、修改和删除功能,第二次作业主要是实现订单的查询和排序功能,第三次作业主要是实现订单的统计和分析功能。通过这三个作业的完成,可以较为全面地掌握一个订单管理系统可能具备的基本功能。编码和逻辑设计:在编写代码的过程中,需要合理设计代码的逻辑和架构。可以通过合理使用函数和模块化编程来划分代码的功能,提高代码的可读性和复用性。同时,还需要考虑合适的数据结构来管理订单记录和菜单选项,以便于进行增删改查等操作。通过这三个作业的完成,可以锻炼对编码和逻辑设计的能力。输入验证和错误处理:在与用户进行交互的过程中,需要进行输入验证和错误处理。编写合适的代码逻辑来验证用户的输入是否合法,避免出现不合法输入导致的错误。当出现错误或异常时,要及时捕获并给出相应的错误提示,提高用户的使用体验。测试和调试:在编写完成后,进行充分的测试和调试是十分重要的。可以通过不同的输入场景和边界条件来测试程序的各种功能,验证程序的正确性和稳定性。同时,要注意捕获并处理可能出现的错误和异常情况。通过测试和调试,可以发现和修复问题,提高代码的质量。总的来说,通过这三次作业的完成,可以提高在订单管理系统开发方面的能力。在编写代码的过程中,需要合理设计代码的逻辑和架构,并注意输入验证和错误处理。还要进行充分的测试和调试,以保证程序的正确性和稳定性。通过不断学习和实践,可以进一步提高自己的编程能力。
标签:return,String,int,blog2,re,str,public From: https://www.cnblogs.com/lt-blog/p/17841755.html