题目集4-6及期中考试

发布时间 2023-11-19 22:25:04作者: 害羞的小可爱

题目集4-6及期中考试

21207218-SZY

前言:

       显而易见,这三次的题目集呈现出了与以往不同的难度,题目4有四道题,而题目5和6都只有一道题,而且完成时间变成了两个星期。题目4主要难度在于是菜单计价程序3,其是在菜单2的基础上增加了更多的细节,而后面题目5,6都是在菜单3上增加了更多要求的两个不同迭代分支,同属菜单计价程序系列,但是难度却比3增加了很多,而且代码的长度肉眼可见的增加了很多行。菜单计价程序3比菜单2增加了两项内容,桌号标识和代点菜信息,需要注意的是最后每一桌总价的计价方式出现了一些微小的变化;菜单计价程序4本体大部分内容与菜单计价程序-3相同,只是增加了特色菜的形式以及异常情况的分析,而且需要注意的是特色菜的计价方式折扣也都与普通菜系不太一样;菜单计价程序5在3的基础上增加了如下要求:1、菜单输入时增加特色菜,其中与4非常不同的就是有一个口味度的分析,特色菜的输入格式:菜品名+英文空格+口味类型+英文空格+基础价格+"T"  2、考虑客户订多桌菜的情况,输入时桌号时,增加用户的信息:格式:table+英文空格+桌号+英文空格+":"+英文空格+客户姓名+英文空格+手机号+日期(格式:YYYY/MM/DD)+英文空格+ 时间(24小时制格式: HH/MM/SS)。由此可见菜单计价程序的难度有多大。而期中考试呢,主要就是对我们进行一个很基础的测试,所以题目难度不大,但是由于有时间限制,很多人可能没有及时写出来,其中最难的当属最后一题,它也是一个迭代的题目,需要利用到很多的设计模式,也需要小心一点。

设计与分析:

 1. PTA4:

菜单计价程序3:

设计点菜计价程序,根据输入的信息,计算并输出总价格。

输入内容按先后顺序包括两部分:菜单、订单,最后以"end"结束。

菜单由一条或多条菜品记录组成,每条记录一行

每条菜品记录包含:菜名、基础价格 两个信息。

订单分:桌号标识、点菜记录和删除信息、代点菜信息。每一类信息都可包含一条或多条记录,每条记录一行或多行。

桌号标识独占一行,包含两个信息:桌号、时间。

桌号以下的所有记录都是本桌的记录,直至下一个桌号标识。

点菜记录包含:序号、菜名、份额、份数。份额可选项包括:1、2、3,分别代表小、中、大份。

不同份额菜价的计算方法:小份菜的价格=菜品的基础价格。中份菜的价格=菜品的基础价格1.5。小份菜的价格=菜品的基础价格2。如果计算出现小数,按四舍五入的规则进行处理。

删除记录格式:序号 delete

标识删除对应序号的那条点菜记录。

如果序号不对,输出"delete error"

代点菜信息包含:桌号 序号 菜品名称 份额 分数

代点菜是当前桌为另外一桌点菜,信息中的桌号是另一桌的桌号,带点菜的价格计算在当前这一桌。

程序最后按输入的先后顺序依次输出每一桌的总价(注意:由于有代点菜的功能,总价不一定等于当前桌上的菜的价格之和)。

每桌的总价等于那一桌所有菜的价格之和乘以折扣。如存在小数,按四舍五入规则计算,保留整数。

折扣的计算方法(注:以下时间段均按闭区间计算):

周一至周五营业时间与折扣:晚上(17:00-20:30)8折,周一至周五中午(10:30--14:30)6折,其余时间不营业。

周末全价,营业时间:9:30-21:30

如果下单时间不在营业范围内,输出"table " + t.tableNum + " out of opening hours"

菜单2的代码:

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

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Order order = new Order();
        Menu menu = new Menu();
        String line = "";
        line = scanner.nextLine();
        String[] items = new String[10];
        int dishCount = 0;
        int recordCount = 0;
        while (!line.equals("end")) { 
            items = line.split(" ");
            if (items.length == 2 && !items[1].equals("delete")) {
                int portion = Integer.parseInt(items[1]);
                Dish dish = menu.addDish(items[0], portion);
                if (dish != null) {
                    menu.dishes[dishCount] = dish;
                    dishCount++;
                }
            }
            if (items.length == 4) {
                int orderNum = Integer.parseInt(items[0]);
                int portion = Integer.parseInt(items[2]);
                int num = Integer.parseInt(items[3]);
                Record record = order.addRecord(orderNum, items[1], portion, num, menu);
                if (record != null) {
                    System.out.println(record.orderNum + " " + record.dish.name + " " + record.getPrice());
                    order.records[recordCount] = record;
                    recordCount++;
                }
            }
            if (items.length == 2 && items[1].equals("delete")) { 
                int orderNum = Integer.parseInt(items[0]);
                order.deleteRecordByOrderNum(orderNum);
            }
            line = scanner.nextLine();
        }
        System.out.println(order.getTotalPrice());
    }
}

class Dish {
    String name;
    int unitPrice;
    
    int getPrice(int portion) {
        switch (portion) {
            case 1:
                return unitPrice;
            case 2:
                if (unitPrice == 15 || unitPrice == 9)
                    return ((int) (unitPrice * 1.5)) + 1;
                else
                    return unitPrice * 3 / 2;
            case 3:
                return unitPrice * 2;
        }
        return 0;
    }
}

class Student {
    private String num;
    private String name;
    private int chinese;
    private int math;
    private int physics;
    
    public Student(String num, String name, int chinese, int math, int physics) {
        this.num = num;
        this.name = name;
        this.chinese = chinese;
        this.math = math;
        this.physics = physics;
    }
    
    public String getNum() {
        return num;
    }
    
    public String getName() {
        return name;
    }
    
    public int getChinese() {
        return chinese;
    }
    
    public int getMath() {
        return math;
    }
    
    public int getPhysics() {
        return physics;
    }
    
    public int getTotal() {
        return chinese + math + physics;
    }
    
    public double getAverage() {
        return (double) getTotal() / 3;
    }
}

class Menu {
    HashMap<String, Dish> dishes = new HashMap<>();
    int dishCount = 0;
    
    Dish searchDishByName(String dishName) {
        return dishes.get(dishName);
    }
    
    Dish addDish(String dishName, int unitPrice) {
        if (dishes.containsKey(dishName)) {
            System.out.println(dishName + " already exists in the menu");
            return null;
        }
        Dish dish = new Dish();
        dish.name = dishName;
        dish.unitPrice = unitPrice;
        dishes.put(dishName, dish);
        dishCount++;
        return dish;
    }
}

class LeapYearChecker {
    public static void main(String[] args) {
        int year = 2024;
        if (isLeapYear(year)) {
            System.out.println(year + " is a leap year");
        } else {
            System.out.println(year + " is not a leap year");
        }
    }
  
    public static boolean isLeapYear(int year) {
        if (year % 4 != 0) {
            return false;
        } else if (year % 100 != 0) {
            return true;
        } else if (year % 400 != 0) {
            return false;
        } else {
            return true;
        }
    }
}

class Record {
    int orderNum;
    Dish dish;
    int portion;
    int num;
    
    Record(int orderNum, Dish dish, int portion, int num) {
        this.orderNum = orderNum;
        this.dish = dish;
        this.portion = portion;
        this.num = num;
    }
    
    int getPrice() {
        return num * dish.getPrice(portion);
    }
}

class Order {
    Record[] records = new Record[10];
    int recordCount = 0;
  
    int getTotalPrice() {
        int totalPrice = 0;
        for (int i = 0; i < recordCount; i++) {
            if (records[i] != null && records[i].dish != null)
                totalPrice += records[i].getPrice();
        }
        return totalPrice;
    }
  
    Record addRecord(int orderNum, String dishName, int portion, int num, Menu menu) {
        if (recordCount >= records.length) {
            System.out.println("Order is full");
            return null;
        }
      
        Dish dish = menu.searchDishByName(dishName);
        if (dish == null) {
            System.out.println(dishName + " does not exist in the menu");
            return null;
        }
      
        Record record = new Record(orderNum, dish, portion, num);
        records[recordCount] = record;
        recordCount++;
        return record;
    }
  
    void deleteRecordByOrderNum(int orderNum) {
        for (int i = 0; i < recordCount; i++) {
            if (records[i] != null && records[i].orderNum == orderNum) {
                records[i] = null;
                return;
            }
        }
        System.out.println("No record found with order number: " + orderNum);
    }
}
View Code

 

2.pta5:

菜单计价程序4:

本次课题比菜单计价系列-3增加的异常情况:

1、菜谱信息与订单信息混合,应忽略夹在订单信息中的菜谱信息。输出:"invalid dish"

2、桌号所带时间格式合法(格式见输入格式部分说明,其中年必须是4位数字,月、日、时、分、秒可以是1位或2位数),数据非法,比如:2023/15/16 ,输出桌号+" date error"

3、同一桌菜名、份额相同的点菜记录要合并成一条进行计算,否则可能会出现四舍五入的误差。

4、重复删除,重复的删除记录输出"deduplication :"+序号。

5、代点菜时,桌号不存在,输出"Table number :"+被点菜桌号+" does not exist";本次作业不考虑两桌记录时间不匹配的情况。

6、菜谱信息中出现重复的菜品名,以最后一条记录为准。

7、如果有重复的桌号信息,如果两条信息的时间不在同一时间段,(时段的认定:周一到周五的中午或晚上是同一时段,或者周末时间间隔1小时(不含一小时整,精确到秒)以内算统一时段),此时输出结果按不同的记录分别计价。

8、重复的桌号信息如果两条信息的时间在同一时间段,此时输出结果时合并点菜记录统一计价。前提:两个的桌号信息的时间都在有效时间段以内。计算每一桌总价要先合并符合本条件的饭桌的点菜记录,统一计价输出。

9、份额超出范围(1、2、3)输出:序号+" portion out of range "+份额,份额不能超过1位,否则为非法格式,参照第13条输出。

10、份数超出范围,每桌不超过15份,超出范围输出:序号+" num out of range "+份数。份数必须为数值,最高位不能为0,否则按非法格式参照第16条输出。

11、桌号超出范围[1,55]。输出:桌号 +" table num out of range",桌号必须为1位或多位数值,最高位不能为0,否则按非法格式参照第16条输出。

12、菜谱信息中菜价超出范围(区间(0,300)),输出:菜品名+" price out of range "+价格,菜价必须为数值,最高位不能为0,否则按非法格式参照第16条输出。

13、时间输入有效但超出范围[2022.1.1-2023.12.31],输出:"not a valid time period"

14、一条点菜记录中若格式正确,但数据出现问题,如:菜名不存在、份额超出范围、份数超出范围,按记录中从左到右的次序优先级由高到低,输出时只提示优先级最高的那个错误。

15、每桌的点菜记录的序号必须按从小到大的顺序排列(可以不连续,也可以不从1开始),未按序排列序号的输出:"record serial number sequence error"。当前记录忽略。(代点菜信息的序号除外)

16、所有记录其它非法格式输入,统一输出"wrong format"

17、如果记录以“table”开头,对应记录的格式或者数据不符合桌号的要求,那一桌下面定义的所有信息无论正确或错误均忽略,不做处理。如果记录不是以“table”开头,比如“tab le 55 2023/3/2 12/00/00”,该条记录认为是错误记录,后面所有的信息并入上一桌一起计算。

本次作业比菜单计价系列-3增加的功能:

菜单输入时增加特色菜,特色菜的输入格式:菜品名+英文空格+基础价格+"T"

例如:麻婆豆腐 9 T

菜价的计算方法:

周一至周五 7折, 周末全价。

注意:不同的四舍五入顺序可能会造成误差,请按以下步骤累计一桌菜的菜价:

计算每条记录的菜价:将每份菜的单价按份额进行四舍五入运算后,乘以份数计算多份的价格,然后乘以折扣,再进行四舍五入,得到本条记录的最终支付价格。

最后将所有记录的菜价累加得到整桌菜的价格。

Dish {

String name;//菜品名称

int unit_price; //单价

int getPrice(int portion)//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份) }
Menu {

Dish[] dishs ;//菜品数组,保存所有菜品信息

Dish searthDish(String dishName)//根据菜名在菜谱中查找菜品信息,返回Dish对象。

Dish addDish(String dishName,int unit_price)//添加一道菜品信息

}
Record {

int orderNum;//序号

Dish d;//菜品\\

int portion;//份额(1/2/3代表小/中/大份)

int getPrice()//计价,计算本条记录的价格

}
Order {

Record[] records;//保存订单上每一道的记录

int getTotalPrice()//计算订单的总价

Record addARecord(int orderNum,String dishName,int portion,int num)//添加一条菜品信息到订单中。

delARecordByOrderNum(int orderNum)//根据序号删除一条记录

findRecordByNum(int orderNum)//根据序号查找一条记录

}

 

菜单4的代码:

import java.text.*;
import java.time.*;
import java.util.*;

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<>();
        Scanner input = new Scanner(System.in);
        String str1;
        int i;
        int size, number;

        while (true) {// 输入菜单
            Dish t = new Dish();
            int isrepeat;
            str1 = input.nextLine();
            if (str1.matches("\\S* [1-9]\\d*")) {
                String[] take = str1.split(" ");
                t.name = take[0];
                t.u_price = Integer.parseInt(take[1]);
                if (t.u_price > 300) {
                    System.out.println(t.name + " price out of range " + t.u_price);
                    continue;
                }
                t.isT = false;
                isrepeat = menu.searchDish(t.name);
                if (isrepeat != -1) {
                    menu.dishs.remove(isrepeat);
                }
                menu.dishs.add(t);
            } else if (str1.matches("\\S* \\d* T")) {
                String[] take = str1.split(" ");
                t.name = take[0];
                t.u_price = Integer.parseInt(take[1]);
                if (t.u_price > 300) {
                    System.out.println(t.name + " price out of range " + t.u_price);
                    continue;
                }
                t.isT = true;
                menu.dishs.add(t);
            } else if (str1.equals("end")) {
                break;
            } else if (str1.matches("tab.*")) {
                break;

            } else {
                System.out.println("wrong format");
            }
        }
        while (!str1.equals("end")) {
            Table t = 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[] take = str1.split(" ");
                    String[] Date = take[2].split("/");
                    String[] Time = take[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]);
                    }
                    t.num = Integer.parseInt(take[1]);
                    if (t.num > 55) {
                        System.out.println(t.num + " table num out of range");
                        str1 = input.nextLine();
                        continue;

                    }
                    try {
                        t.time = LocalDateTime.of(intDate[0], intDate[1], intDate[2], intTime[0], intTime[1],
                                intTime[2]);
                        t.getWeekDay();
                    } catch (DateTimeException e) {
                        System.out.println(t.num + " date error");
                        str1 = input.nextLine();
                        continue;
                    }
                    if (!(t.time.isAfter(LocalDateTime.of(2022, 1, 1, 0, 0, 0))
                            && t.time.isBefore(LocalDateTime.of(2024, 1, 1, 0, 0, 0)))) {
                        System.out.println("not a valid time period");
                        str1 = input.nextLine();
                        continue;
                    }
                    // 判断桌号是否重复
                    if (t.isOpen()) {
                        for (Table table : tables) {
                            if (t.num == table.num && table.isOpen() && t.time.toLocalDate().isEqual(table.time.toLocalDate())) {
                                Duration duration = Duration.between(t.time, table.time);

                                if ((t.weekday > 0 && t.weekday < 6) && (t.time.getHour() < 15 && table.time.getHour() < 15)) {
                                    t = table;
                                    isrepeat = true;
                                    repeatNum = i;
                                    break;
                                } else if (!(t.weekday > 0 && t.weekday < 6) && duration.abs().toMinutes() <= 60) {
                                    t = table;
                                    repeatNum = i;
                                    isrepeat = true;
                                    break;
                                }
                            }
                        }
                    }
                    if(!isrepeat) {
                        System.out.println("table " + t.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[] take = str1.split(" ");
                        size = Integer.parseInt(take[2]);
                        number = Integer.parseInt(take[3]);

                        if (t.order.records.size() > 0) {
                            if (Integer.parseInt(take[0]) <= t.order.records.get(t.order.records.size() - 1).orderNum) {
                                System.out.println("record serial number sequence error");
                                continue;
                            }
                        }

                        // 菜品不存在
                        if (menu.searchDish(take[1]) == -1) {
                            System.out.println(take[1] + " does not exist");
                            continue;
                        }

                        // 尺寸超出范围
                        if (size > 3 || size < 1) {
                            System.out.println(Integer.parseInt(take[0]) + " size out of range " + size);
                            continue;
                        }

                        // 数量超出范围
                        if (number > 15) {
                            System.out.println(Integer.parseInt(take[0]) + " num out of range " + number);
                            continue;
                        }

                        t.od(menu, take[0], take[1], size, number);
                    }
                    // 判断是否为删除订单
                    else if (str1.matches("[1-9]\\d* delete")) {
                        String[] take = str1.split(" ");
                        t.order.delARecordByOrderNum(Integer.parseInt(take[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[] take = str1.split(" ");
                        // 判断代点桌号是否存在
                        boolean exist = false;
                        for (Table table : tables) {
                            if (table.num == Integer.parseInt(take[0])) {
                                exist = true;
                                break;
                            }
                        }
                        if (exist) {
                            System.out.print(Integer.parseInt(take[1]) + " table " + t.num + " pay for table "
                                    + Integer.parseInt(take[0]) + " ");
                            Record treat = new Record();
                            treat.d = menu.dishs.get(menu.searchDish(take[2]));
                            size = Integer.parseInt(take[3]);
                            number = Integer.parseInt(take[4]);
                            treat.size = size;
                            treat.number = number;
                            System.out.print(treat.getPrice() + "\n");
                            t.sum += treat.getPrice();
                        }
                        // 若不存在则输出内容
                        else {
                            System.out.println("Table number :" + Integer.parseInt(take[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;
                t = tables.get(tables.size());
                while (true) {
                    str1 = input.nextLine();
                    if (str1.matches("[1-9]\\d* \\S* \\d [1-9]\\d*")) {
                        String[] take = str1.split(" ");
                        size = Integer.parseInt(take[2]);
                        number = Integer.parseInt(take[3]);
                        // 判断订单号是否由小到大排列
                        if (t.order.records.size() > 0) {
                            if (Integer.parseInt(
                                    take[0]) <= t.order.records.get(t.order.records.size() - 1).orderNum) {
                                System.out.println("record serial number sequence error");
                                continue;
                            }
                        }
                        if (menu.searchDish(take[1]) == -1) {
                            System.out.println(take[1] + " does not exist");
                            continue;
                        }
                        if (size > 3 || size < 1) {
                            System.out.println(Integer.parseInt(take[0]) + " size out of range " + size);
                            continue;
                        }
                        if (number > 15) {
                            System.out.println(Integer.parseInt(take[0]) + " num out of range " + number);
                            continue;
                        }
                        t.od(menu, take[0], take[1], size, number);
                    }
                    // 判断是否为删除订单
                    else if (str1.matches("[1-9]\\d* delete")) {
                        String[] take = str1.split(" ");
                        t.order.delARecordByOrderNum(Integer.parseInt(take[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[] take = str1.split(" ");
                        // 判断代点桌号是否存在
                        boolean exist = false;
                        for (Table table : tables) {
                            if (table.num == Integer.parseInt(take[0])) {
                                exist = true;
                                break;
                            }
                        }
                        if (exist) {
                            System.out.print(Integer.parseInt(take[1]) + " table " + t.num + " pay for table "
                                    + Integer.parseInt(take[0]) + " ");
                            Record treat = new Record();
                            treat.d = menu.dishs.get(menu.searchDish(take[2]));
                            size = Integer.parseInt(take[3]);
                            number = Integer.parseInt(take[4]);
                            treat.size = size;
                            treat.number = number;
                            System.out.print(treat.getPrice() + "\n");
                            t.sum += treat.getPrice();
                        }
                        // 若不存在则输出内容
                        else {
                            System.out.println("Table number :" + Integer.parseInt(take[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(t.order.records);
                }
            } else {
                str1 = input.nextLine();
                continue;
            }

            // 本桌点菜结束,进入下一桌
            if (isrepeat) {
                tables.remove(repeatNum);
            }
            t.getSum();
            tables.add(t);
        }
        // 最终输出桌号订单信息
        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   1 " + tables.get(i).num + "  out of opening hours");
        }
    }

    static class Dish {
        String name;
        int u_price;
        boolean isT = false;
    }

    static class Record {
        int orderNum;
        Dish d;
        int size;
        int number;
        boolean isDeleted = false;

        int getPrice() {
            int price;

            switch (size) {
                case 1:
                    price = (int) Math.round(d.u_price);
                    break;
                case 2:
                    price = (int) Math.round(1.5 * d.u_price);
                    break;
                case 3:
                    price = (int) Math.round(2 * d.u_price);
                    break;
                default:
                    System.out.println(orderNum + " portion out of range " + size);
                    return -1; // 返回 -1 表示非法格式
            }

            return price * number;
        }
    }

    static class Menu {
        List<Dish> dishs = new ArrayList<>();

        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 u_price) {
            Dish newDish = new Dish();
            newDish.name = dishName;
            newDish.u_price = u_price;
            return newDish;
        }
    }

    static class Order {
        //        Record[] records = new Record[20];
        ArrayList<Record> records = new ArrayList<>();

        Record addARecord(int orderNum, String dishName, int size, int number, Menu menu) {
            Record newRecord = new Record();
            newRecord.orderNum = orderNum;
            newRecord.d = menu.dishs.get(menu.searchDish(dishName));
            newRecord.size = size;
            newRecord.number = number;
            System.out.println(newRecord.orderNum + " " + newRecord.d.name + " " + newRecord.getPrice());
            return newRecord;
        }

        int searchRecord(String name) {
            Record recordToFind = new Record();
            recordToFind.d.name = name;

            int index = records.indexOf(recordToFind);

            if (index == -1) {
                System.out.println("Record not found.");
            }

            return index;
        }


        boolean 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;");
                return false;
            }
            return true;
        }
    }

    static class Table {
        Order order = new Order();
        int num;
        LocalDateTime time;
        int weekday;
        long sum = 0;
        long origSum = 0;

        void od(Menu menu, String str1, String str2, int size, int number) {
            {
                order.records.add(order.addARecord(Integer.parseInt(str1), str2, size, number, menu));

            }
        }

        void getWeekDay() {
            weekday = time.getDayOfWeek().getValue();
        }

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

        }

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

    }

    public class Calculator {
        public int add(int a, int b) {
            return a + b;
        }

        public int subtract(int a, int b) {
            return a - b;
        }

        public int multiply(int a, int b) {
            return a * b;
        }

        public double divide(int a, int b) {
            if (b == 0) {
                throw new IllegalArgumentException("Divisor cannot be zero.");
            }
            return (double) a / b;
        }
    }
    public class Book {
        private String title;
        private String author;
        private String publisher;
        private boolean borrowed;

        public Book(String title, String author, String publisher) {
            this.title = title;
            this.author = author;
            this.publisher = publisher;
            this.borrowed = false;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String author) {
            this.author = author;
        }

        public String getPublisher() {
            return publisher;
        }

        public void setPublisher(String publisher) {
            this.publisher = publisher;
        }

        public boolean isBorrowed() {
            return borrowed;
        }

        public void borrow() {
            if (borrowed) {
                System.out.println("This book has already been borrowed.");
            } else {
                borrowed = true;
                System.out.println("Successfully borrowed " + title);
            }
        }

        public void returnBook() {
            if (borrowed) {
                borrowed = false;
                System.out.println("Successfully returned " + title);
            } else {
                System.out.println("This book has not been borrowed yet.");
            }
        }
    }
    public class Person {
        private String name;
        private int age;
        private String gender;

        public Person(String name, int age, String gender) {
            this.name = name;
            this.age = age;
            this.gender = gender;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getGender() {
            return gender;
        }

        public void setGender(String gender) {
            this.gender = gender;
        }

        public void eat() {
            System.out.println(name + " is eating.");
        }

        public void sleep() {
            System.out.println(name + " is sleeping.");
        }
    }
}
View Code

代码分析:

1.菜品类:对应菜谱上一道菜的信息。

2.菜谱类:对应菜谱,包含饭店提供的所有菜的信息。

3.点菜记录类:保存订单上的一道菜品记录。

4.订单类:保存用户点的所有菜的信息。

5.Table类:保留桌号,时间等信息,从而计算各桌总价。

  1. 程序需求分析:

    • 输入:用户需要输入点菜信息,包括菜品名称和数量。
    • 输出:程序需要输出点菜总价。
    • 功能:根据用户输入的菜品和数量,计算并输出点菜总价。
  2. 数据结构设计:

    • 菜单:可以使用字典或者数据库存储菜单信息,其中菜品名称作为键,对应的价格作为值。
    • 点菜信息:可以使用列表或者字典存储用户点菜信息,其中菜品名称作为键,对应的数量作为值。
  3. 程序流程设计:

    • 初始化菜单和点菜信息为空。
    • 显示菜单供用户选择,并提示用户输入菜品和数量。
    • 根据用户输入更新点菜信息。
    • 当用户不再点菜时,计算点菜总价。
    • 输出点菜总价。

3.PTA6:

菜单计价程序5:

1、菜单输入时增加特色菜,特色菜的输入格式:菜品名+英文空格+口味类型+英文空格+基础价格+"T"

例如:麻婆豆腐 川菜 9 T

菜价的计算方法:

周一至周五 7折, 周末全价。

特色菜的口味类型:川菜、晋菜、浙菜

川菜增加辣度值:辣度0-5级;对应辣度水平为:不辣、微辣、稍辣、辣、很辣、爆辣;

晋菜增加酸度值,酸度0-4级;对应酸度水平为:不酸、微酸、稍酸、酸、很酸;

浙菜增加甜度值,甜度0-3级;对应酸度水平为:不甜、微甜、稍甜、甜;    

例如:麻婆豆腐 川菜 9 T

输入订单记录时如果是特色菜,添加口味度(辣/酸/甜度)值,格式为:序号+英文空格+菜名+英文空格+口味度值+英文空格+份额+英文空格+份数

例如:1 麻婆豆腐 4 1 9

单条信息在处理时,如果口味度超过正常范围,输出"spicy/acidity/sweetness num out of range : "+口味度值,spicy/acidity/sweetness(辣度/酸度/甜度)根据菜品类型择一输出,例如:

acidity num out of range : 5

输出一桌的信息时,按辣、酸、甜度的顺序依次输出本桌菜各种口味的口味度水平,如果没有某个类型的菜,对应的口味(辣/酸/甜)度不输出,只输出已点的菜的口味度。口味度水平由口味度平均值确定,口味度平均值只综合对应口味菜系的菜计算,不做所有菜的平均。比如,某桌菜点了3份川菜,辣度分别是1、3、5;还有4份晋菜,酸度分别是,1、1、2、2,辣度平均值为3、酸度平均值四舍五入为2,甜度没有,不输出。

一桌信息的输出格式:table+英文空格+桌号+:+英文空格+当前桌的原始总价+英文空格+当前桌的计算折扣后总价+英文空格+"川菜"+数量+辣度+英文空格+"晋菜"+数量+酸度+英文空格+"浙菜"+数量+甜度。

如果整桌菜没有特色菜,则只输出table的基本信息,格式如下,注意最后加一个英文空格:

table+英文空格+桌号+:+英文空格+当前桌的原始总价+英文空格+当前桌的计算折扣后总价+英文空格

例如:table 1: 60 36 川菜 2 爆辣 浙菜 1 微甜

计算口味度时要累计本桌各类菜系所有记录的口味度总和(每条记录的口味度乘以菜的份数),再除以对应菜系菜的总份数,最后四舍五入。

注:本题要考虑代点菜的情况,当前桌点的菜要加上被其他桌代点的菜综合计算口味度平均值。

2、考虑客户订多桌菜的情况,输入时桌号时,增加用户的信息:

格式:table+英文空格+桌号+英文空格+":"+英文空格+客户姓名+英文空格+手机号+日期(格式:YYYY/MM/DD)+英文空格+ 时间(24小时制格式: HH/MM/SS)

例如:table 1 : tom 13670008181 2023/5/1 21/30/00

约束条件:客户姓名不超过10个字符,手机号11位,前三位必须是180、181、189、133、135、136其中之一。

输出结果时,先按要求输出每一桌的信息,最后按字母顺序依次输出每位客户需要支付的金额。不考虑各桌时间段的问题,同一个客户的所有table金额都要累加。

输出用户支付金额格式:

用户姓名+英文空格+手机号+英文空格+支付金额

 菜单5的代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        Dish[] dishes = new Dish[20];
        SpecialDish[] specialDishes = new SpecialDish[20];
        ArrayList<Table> tables = new ArrayList<>();
        Table table = new Table();
        Record[] records = new Record[20];
        PersonPay[] personPays = new PersonPay[10];
        Order order = new Order();
        Menu menu = new Menu();
        lastPrint print = new lastPrint();
        int x = 0 , y = 0 , z = 0 , z1 = 0 , p = 0 , tableNum , dishNum , portion , num , unit_price , deleteNum , tasteNum;
        String menuName , dayTime , hourTime , name , tableName , telephoneNum , taste;
        boolean isHaveTable = false , forOther = false;
        for(;;){
            String input = in.readLine();
            if(input.equals("end")){
                if(x!=0){
                    table.order = order;
                    tables.add(x-1 , table);
                }
                print.tables = tables;
                print.personPays = personPays;
                print.print();
                print.payPrint();
                break;
            }
            String[] getInput = input.split(" ");
            if(input.matches("^(table)( )([1-9][0-9]*)( )(:)( )(\\S+)( )((136|133|135|180|181|189)[0-9]{8})( )([0-9]{4})(/)([0-9]|[0-9]{2})(/)([0-9]|[0-9]{2})( )([0-9]|[0-9]{2})(/)([0-9]|[0-9]{2})(/)([0-9]|[0-9]{2})$")) {
                if(x != 0) {
                    table.order = order;
                    tables.add(x-1 , table);
                    table = new Table();
                    y = 0;
                }
                isHaveTable = true;
                tableNum = Integer.parseInt(getInput[1]);
                tableName = getInput[3];
                telephoneNum = getInput[4];
                dayTime = getInput[5];
                hourTime = getInput[6];
                table.tableNum = tableNum;
                table.tableName = tableName;
                table.telephoneNum = telephoneNum;
                table.mainTime = dayTime;
                table.remainTime = hourTime;
                if(!table.timeJudgement1()){
                    isHaveTable = false;
                    System.out.println("table " +table.tableNum + " out of opening hours");
                    continue;
                }
                order = new Order();
                records = new Record[10];
                if(x==0){
                    personPays[p] = new PersonPay();
                    personPays[p].name = tableName;
                    personPays[p].telephoneNum = telephoneNum;
                    p++;
                    print.p = p;
                }
                else{
                    for(int i=0;i<p;i++){
                        if(personPays[i].name.equals(tableName)&&personPays[i].telephoneNum.equals(telephoneNum))
                            break;
                        if(i==p-1){
                            personPays[p] = new PersonPay();
                            personPays[p].name = tableName;
                            personPays[p].telephoneNum = telephoneNum;
                            p++;
                            print.p = p;
                        }
                    }
                }
                System.out.println("table "+tableNum+": ");
                x++;
            }
            else if(input.matches("^(\\S+)( )([1-9][0-9]*)$")){
                int i = 0;
                menuName = getInput[0];
                unit_price = Integer.parseInt(getInput[1]);
                if(z == 0) {
                    dishes[0] = menu.addDish(menuName , unit_price);
                    z++;
                }
                else{
                    for(;i < z ; i++) {
                        if(menuName.equalsIgnoreCase(dishes[i].name)) {
                            dishes[i].unit_price = unit_price;
                            break;
                        }
                    }
                }
                if(i == z){
                    dishes[z] = menu.addDish(menuName , unit_price);
                    z++;
                }
                menu.dishes = dishes;
                menu.dishNum = z;
            }
            else if(input.matches("^(\\S+)( )(\\S+)( )([1-9][0-9]*)( )(T)$")){
                int i = 0;
                menuName = getInput[0];
                taste = getInput[1];
                unit_price = Integer.parseInt(getInput[2]);
                if(z1 == 0) {
                    specialDishes[0] = menu.addSpecialDish(menuName , unit_price , taste);
                    z1++;
                }
                else{
                    for(;i < z1 ; i++) {
                        if(menuName.equalsIgnoreCase(specialDishes[i].name)) {
                            specialDishes[i].unit_price = unit_price;
                            break;
                        }
                    }
                }
                if(i == z1){
                    specialDishes[z1] = menu.addSpecialDish(menuName , unit_price , taste);
                    z1++;
                }
                menu.specialDishes = specialDishes;
                menu.dishNum1 = z1;
            }
            else if(input.matches("^([1-9][0-9]*)( )(\\S+)( )([1-9][0-9]*)( )([1-9][0-9]*)$")){
                if(!isHaveTable)
                    continue;
                dishNum = Integer.parseInt(getInput[0]);
                name = getInput[1];
                portion = Integer.parseInt(getInput[2]);
                num = Integer.parseInt(getInput[3]);
                if(menu.searthDish(name) != null) {
                    records[y] = new Record();
                    records[y] = order.addARecord(dishNum , name , portion , num , menu);
                    records[y].isSpecialDish = false;
                    System.out.println(records[y].orderNum+" "+records[y].d.name+" "+records[y].getPrice());
                    y++;
                    order.records = records;
                    order.dishNum = y;
                }
                else{
                    System.out.println(name+" does not exist");
                }
            }
            else if(input.matches("^([1-9][0-9]*)( )(\\S+)( )([0-9]+)( )([1-9][0-9]*)( )([1-9][0-9]*)$")){
                if(!isHaveTable)
                    continue;
                dishNum = Integer.parseInt(getInput[0]);
                name = getInput[1];
                tasteNum = Integer.parseInt(getInput[2]);
                portion = Integer.parseInt(getInput[3]);
                num = Integer.parseInt(getInput[4]);
                if(menu.searthSpecialDish(name) != null) {
                    if(((menu.searthSpecialDish(name).taste.equals("川菜") && tasteNum >= 0 && tasteNum <= 5) || (menu.searthSpecialDish(name).taste.equals("晋菜") && tasteNum>=0 && tasteNum <= 4) || (menu.searthSpecialDish(name).taste.equals("浙菜") && tasteNum>=0 && tasteNum <= 3))){
                        records[y] = new Record();
                        records[y] = order.addASpecialRecord(dishNum , name , portion , num , menu , tasteNum , forOther);
                        records[y].isSpecialDish = true;
                        System.out.println(records[y].orderNum+" "+records[y].d.name+" "+records[y].getPrice());
                        y++;
                        order.records = records;
                        order.dishNum = y;
                    }
                }
                else{
                    System.out.println(name+" does not exist");
                    continue;
                }
 if(menu.searthSpecialDish(name).taste.equals("川菜")){
                    if(tasteNum<0||tasteNum>5)
                        System.out.println("spicy num out of range :"+tasteNum);
                }
                if(menu.searthSpecialDish(name).taste.equals("晋菜")){
                    if(tasteNum<0||tasteNum>4)
                        System.out.println("acidity num out of range :"+tasteNum);
                }
                if(menu.searthSpecialDish(name).taste.equals("浙菜")){
                    if(tasteNum<0||tasteNum>3)
                        System.out.println("sweetness num out of range :"+tasteNum);
                }
            }
            else if(input.matches("([1-9][0-9]*)( )(delete)")) {
                if(!isHaveTable)
                    continue;
                deleteNum = Integer.parseInt(getInput[0]);
                if(order.findRecordByNum(deleteNum) == 1){
                    order.delARecordByOrderNum(deleteNum);
                }
                else
                    System.out.println("delete error;");
            }
            else if(input.matches("^([1-9][0-9]*)( )([1-9][0-9]*)( )(\\S+)( )([1-9][0-9]*)( )([1-9][0-9]*)$")) {
                if(!isHaveTable)
                    continue;
                int t = Integer.parseInt(getInput[0]);
                dishNum = Integer.parseInt(getInput[1]);
                name = getInput[2];
                portion = Integer.parseInt(getInput[3]);
                num = Integer.parseInt(getInput[4]);
                for(int i = 0;i<x-1;i++){
                    if(tables.get(i).tableNum == t){
                        if(menu.searthDish(name) != null) {
                            records[y] = new Record();
                            records[y] = order.addARecord(dishNum , name , portion , num , menu);
                            records[y].isSpecialDish = false;
                            System.out.println(dishNum+" table "+table.tableNum+" pay for table "+t+" "+records[y].getPrice());
                            y++;
                            order.records = records;
                            order.dishNum = y;
                        }
                        break;
                    }
                }
            }
            else if(input.matches("^([1-9][0-9]*)( )([1-9][0-9]*)( )(\\S+)( )([0-9]*)( )([1-9][0-9]*)( )([1-9][0-9]*)$")) {
                if(!isHaveTable)
                    continue;
                int t = Integer.parseInt(getInput[0]);
                dishNum = Integer.parseInt(getInput[1]);
                name = getInput[2];
                tasteNum = Integer.parseInt(getInput[3]);
                portion = Integer.parseInt(getInput[4]);
                num = Integer.parseInt(getInput[5]);
                for(int i = 0;i<x-1;i++){
                    if(tables.get(i).tableNum == t){
                        if(menu.searthSpecialDish(name) != null) {
                            if(((menu.searthSpecialDish(name).taste.equals("川菜") && tasteNum >= 1 && tasteNum <= 5) || (menu.searthSpecialDish(name).taste.equals("晋菜") && tasteNum <= 4) || (menu.searthSpecialDish(name).taste.equals("浙菜") && tasteNum <= 3))){
                                records[y] = new Record();
                                records[y] = order.addASpecialRecord(dishNum , name , portion , num , menu , tasteNum , !forOther);
                                records[y].isSpecialDish = true;
                                System.out.println(dishNum+" table "+table.tableNum+" pay for table "+t+" "+records[y].getPrice());
                                tables.get(i).giveTaste(name,num,tasteNum,menu);
                                y++;
                                order.records = records;
                                order.dishNum = y;
                            }
                        }

                        break;
                    }
                }
            }
            else {
                System.out.println("wrong format");
            }
        }
    }
}
class Dish{
    String name;
    int unit_price;

    public void setName(String name) {
        this.name = name;
    }

    public void setUnitPrice(int unit_price) {
        this.unit_price = unit_price;
    }
    public int getPrice(int portion) {
        double getPrice = 0; // 用于存储计算后的价格

        switch (portion) {
            case 1:
                getPrice = unit_price;
                break;
            case 2:
                getPrice = unit_price * 1.5;
                break;
            case 3:
                getPrice = unit_price * 2;
                break;
            default:
                // 处理其他份量的情况
                System.out.println("Unsupported portion size");
                break;
        }

        return (int) Math.round(getPrice);
    }
}
class SpecialDish extends Dish{
    String taste;

    public void setTaste(String taste) {
        this.taste = taste;
    }
}
class Menu{
    Dish[] dishes;
    SpecialDish[] specialDishes;
    int dishNum;
    int dishNum1;
    public Dish searthDish(String dishName){
        for(int k=0;k<dishNum;k++) {
            if(dishName.equals(dishes[k].name)){
                return dishes[k];
            }
        }
        return null;
    }
    public SpecialDish searthSpecialDish(String dishName){
        for(int k=0;k<dishNum1;k++) {
            if(dishName.equals(specialDishes[k].name)){
                return specialDishes[k];
            }
        }
        return null;
    }
    public Dish addDish(String dishName, int unitPrice) {
        Dish newDish = new Dish();
        newDish.setName(dishName);
        newDish.setUnitPrice(unitPrice);
        return newDish;
    }

    public SpecialDish addSpecialDish(String dishName, int unitPrice, String taste) {
        SpecialDish newDish = new SpecialDish();
        newDish.setName(dishName);
        newDish.setUnitPrice(unitPrice);
        newDish.setTaste(taste);
        return newDish;
    }
}
class Record{
    int orderNum;
    Dish d;
    int portion;
    int num;
    int spicy;
    int acidity;
    int sweetness;
    boolean isSpecialDish;
    public int getPrice() {
        return d.getPrice(portion)*num;
    }
}
class Order {
    int dishNum;
    int allCommonPrice;
    int allSpecialPrice;
    Record[] records;
    public void addPortion() {
        int k = 0;
        while (k < dishNum - 1) {
            int l = k + 1;
            while (l < dishNum) {
                if (records[k].d.name.equals(records[l].d.name) && records[k].portion == records[l].portion) {
                    records[k].num += records[l].num;
                    records[l].num = 0;
                }
                l++;
            }
            k++;
        }
    }
    public void getTotalPrice(){
        for(int k=0;k<dishNum;k++) {
            if(!records[k].isSpecialDish)
                allCommonPrice+=records[k].getPrice();
            else
                allSpecialPrice+=records[k].getPrice();
        }
    }
    public int getTotalPrice(double commonDiscount,double specialDiscount){
        int all = 0;
        for(int k=0;k<dishNum;k++) {
            if(!records[k].isSpecialDish)
                all+=Math.round(records[k].getPrice()*commonDiscount);
            else
                all+=Math.round(records[k].getPrice()*specialDiscount);
        }
        return all;
    }
    public Record addARecord(int orderNum,String dishName,int portion,int num , Menu menu){
        Record x=new Record();
        x.d=menu.searthDish(dishName);
        x.orderNum=orderNum;
        x.portion=portion;
        x.num=num;
        return x;
    }

    public Record addASpecialRecord(int orderNum,String dishName,int portion,int num ,Menu menu,int tasteNum , boolean forOther){
        Record x=new Record();
        x.d=menu.searthSpecialDish(dishName);
        x.orderNum=orderNum;
        x.portion=portion;
        x.num=num;
        if(!forOther){
            if(menu.searthSpecialDish(dishName).taste.equals("川菜")){
                x.spicy = tasteNum;
                x.acidity = -1;
                x.sweetness = -1;
            }
            if(menu.searthSpecialDish(dishName).taste.equals("晋菜")){
                x.spicy = -1;
                x.acidity = tasteNum;
                x.sweetness = -1;
            }
            if(menu.searthSpecialDish(dishName).taste.equals("浙菜")){
                x.spicy = -1;
                x.acidity = -1;
                x.sweetness = tasteNum;
            }
        }
        else{
            x.spicy = -1;
            x.acidity = -1;
            x.sweetness = -1;
        }
        return x;
    }
    public void delARecordByOrderNum(int orderNum){
        for(int k=0;k<dishNum;k++) {
            if(orderNum==records[k].orderNum) {
                records[k].num=0;
            }
        }
    }
    public int findRecordByNum(int orderNum){
        for(int k = 0; k<dishNum;k++) {
            if(records[k].orderNum==orderNum) {
                return 1;
            }
        }
        return 0;
    }
}
class Table {
    int tableNum;
    String tableName;
    String telephoneNum;
    String mainTime;
    String remainTime;
    Order order;
    double commonDiscount;
    double specialDiscount;
    int averageSpicy;
    int averageAcidity;
    int averageSweetness;
    double spicyNum;
    double acidityNum;
    double sweetnessNum;

    public boolean timeJudgement1() {
        String[] x = remainTime.split("/");
        String[] y = mainTime.split("/");
        int year = Integer.parseInt(y[0]);
        int month = Integer.parseInt(y[1]);
        int day = Integer.parseInt(y[2]);
        double hour = Double.parseDouble(x[0]);
        double minute = Double.parseDouble(x[1]);
        double second = Double.parseDouble(x[2]);
        LocalDate date = LocalDate.of(year, month, day);
        int weekOfDay = date.getDayOfWeek().getValue();
        switch (weekOfDay) {
            case 6:
            case 7:
                if (hour >= 10 && hour < 21) {
                    specialDiscount = commonDiscount = 1;
                    return true;
                } else if (hour == 9 && minute >= 30 || hour == 21 && (minute < 30 || (minute == 30 && second == 0))) {
                    specialDiscount = commonDiscount = 1;
                    return true;
                }
                break;
            default:
                if (weekOfDay >= 1 && weekOfDay <= 5) {
                    if ((hour > 17 && hour < 20) || (hour == 17 && minute >= 0) || (hour == 20 && (minute < 30 || (minute == 30 && second == 0)))) {
                        commonDiscount = 0.8;
                        specialDiscount = 0.7;
                        return true;
                    } else if ((hour > 10 && hour < 14) || (hour == 10 && minute >= 30) || (hour == 14 && (minute < 30 || (minute == 30 && second == 0)))) {
                        commonDiscount = 0.6;
                        specialDiscount = 0.7;
                        return true;
                    }
                }
                break;
        }
        return false;
    }

    public int tablePrice() {
        return this.order.getTotalPrice(commonDiscount, specialDiscount);
    }
    public void getTaste(){
        for(int k = 0;k<this.order.dishNum;k++){
            if(order.records[k].isSpecialDish){
                if(order.records[k].spicy!=-1){
                    averageSpicy+=order.records[k].spicy*order.records[k].num;
                    spicyNum=order.records[k].num+spicyNum;
                }
                if(order.records[k].acidity!=-1){
                    averageAcidity+=order.records[k].acidity*order.records[k].num;
                    acidityNum=order.records[k].num+acidityNum;
                }
                if(order.records[k].sweetness!=-1){
                    averageSweetness+=order.records[k].sweetness*order.records[k].num;
                    sweetnessNum=order.records[k].num+sweetnessNum;
                }
            }
        }
averageSpicy = (spicyNum != 0) ? (int) Math.round(averageSpicy / spicyNum) : 0;
averageAcidity = (acidityNum != 0) ? (int) Math.round(averageAcidity / acidityNum) : 0;
averageSweetness = (sweetnessNum != 0) ? (int) Math.round(averageSweetness / sweetnessNum) : 0;

    }

    public String getTasteLevel(int level) {
        if (level == 0) {
            return "不";
        } else if (level == 1) {
            return "微";
        } else if (level == 2) {
            return "稍";
        } else if (level == 3) {
            return "";
        } else if (level == 4) {
            return "很";
        } else {
            return "爆";
        }
    }

    public String spicyLevel(){
        return getTasteLevel(averageSpicy) + "辣";
    }

    public String acidityLevel(){
        return getTasteLevel(averageAcidity) + "酸";
    }

    public String sweetnessLevel(){
        return getTasteLevel(averageSweetness) + "甜";
    }
    public void giveTaste(String name , int num , int tasteLevel , Menu menu){
        if(menu.searthSpecialDish(name).taste.equals("川菜")){
            averageSpicy+=tasteLevel*num;
            spicyNum+=num;
        }
        if(menu.searthSpecialDish(name).taste.equals("晋菜")){
            averageAcidity+=tasteLevel*num;
            acidityNum+=num;
        }
        if(menu.searthSpecialDish(name).taste.equals("浙菜")){
            averageSweetness+=tasteLevel*num;
            sweetnessNum+=num;
        }
    }

}
class lastPrint {
    ArrayList<Table> tables = new ArrayList<>();
    PersonPay[] personPays;
    int p;

    public void print(){
        for (Table table : tables) {
            table.order.getTotalPrice();
            table.getTaste();
            if(table.spicyNum==0&&table.acidityNum==0&&table.sweetnessNum==0)
                System.out.println("table " + table.tableNum + ": " + (table.order.allCommonPrice + table.order.allSpecialPrice) + " " + table.tablePrice()+" ");
            if(table.spicyNum!=0&&table.acidityNum==0&&table.sweetnessNum==0)
                System.out.println("table " + table.tableNum + ": " + (table.order.allCommonPrice + table.order.allSpecialPrice) + " " + table.tablePrice() + " 川菜 " +(int)table.spicyNum+" "+table.spicyLevel());
            if(table.spicyNum==0&&table.acidityNum!=0&&table.sweetnessNum==0)
                System.out.println("table " + table.tableNum + ": " + (table.order.allCommonPrice + table.order.allSpecialPrice) + " " + table.tablePrice() + " 晋菜 " +(int)table.acidityNum+" "+table.acidityLevel());
            if(table.spicyNum==0&&table.acidityNum==0&&table.sweetnessNum!=0)
                System.out.println("table " + table.tableNum + ": " + (table.order.allCommonPrice + table.order.allSpecialPrice) + " " + table.tablePrice() + " 浙菜 " +(int)table.sweetnessNum+" "+table.sweetnessLevel());
            if(table.spicyNum!=0&&table.acidityNum!=0&&table.sweetnessNum==0)
                System.out.println("table " + table.tableNum + ": " + (table.order.allCommonPrice + table.order.allSpecialPrice) + " " + table.tablePrice() + " 川菜 " +(int)table.spicyNum+" "+table.spicyLevel()+" 晋菜 "+(int)table.acidityNum+" "+table.acidityLevel());
            if(table.spicyNum!=0&&table.acidityNum==0&&table.sweetnessNum!=0)
                System.out.println("table " + table.tableNum + ": " + (table.order.allCommonPrice + table.order.allSpecialPrice) + " " + table.tablePrice() + " 川菜 " +(int)table.spicyNum+" "+table.spicyLevel()+" 浙菜 "+(int)table.sweetnessNum+" "+table.sweetnessLevel());
            if(table.spicyNum==0&&table.acidityNum!=0&&table.sweetnessNum!=0)
                System.out.println("table " + table.tableNum + ": " + (table.order.allCommonPrice + table.order.allSpecialPrice) + " " + table.tablePrice() + " 晋菜 " +(int)table.acidityNum+" "+table.acidityLevel()+" 浙菜 "+(int)table.sweetnessNum+" "+table.sweetnessLevel());
            if(table.spicyNum!=0&&table.acidityNum!=0&&table.sweetnessNum!=0)
                System.out.println("table " + table.tableNum + ": " + (table.order.allCommonPrice + table.order.allSpecialPrice) + " " + table.tablePrice() + " 川菜 " +(int)table.spicyNum+" "+table.spicyLevel()+" 晋菜 "+(int)table.acidityNum+" "+table.acidityLevel()+" 浙菜 "+(int)table.sweetnessNum+" "+table.sweetnessLevel());
        }
    }

public void payPrint(){
        for(int k=0;k<p;k++){
            for(Table table:tables){
                if(table.tableName.equals(personPays[k].name)){
                    personPays[k].payPrice+=table.tablePrice();
                }
            }
        }
        for(int k=0;k<p-1;k++){
            for(int l=k+1;l<p;l++){
                if(personPays[k].name.toLowerCase().compareTo(personPays[l].name.toLowerCase())>0) {
                    PersonPay x;
                    x=personPays[l];
                    personPays[l]=personPays[k];
                    personPays[k]=x;
                }
            }
        }
        for(int k=0;k<p;k++){
            System.out.println(personPays[k].name+" "+personPays[k].telephoneNum+" "+personPays[k].payPrice);
        }
    }
}

class PersonPay{
    String name;
    String telephoneNum;
    int payPrice;
}

class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }

    public int multiply(int a, int b) {
        return a * b;
    }

    public double divide(int a, int b) {
        if (b == 0) {
            throw new IllegalArgumentException("Divisor cannot be zero.");
        }
        return (double) a / b;
    }
}
 class Book {
    private String title;
    private String author;
    private String publisher;
    private boolean borrowed;

    public Book(String title, String author, String publisher) {
        this.title = title;
        this.author = author;
        this.publisher = publisher;
        this.borrowed = false;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public boolean isBorrowed() {
        return borrowed;
    }

    public void borrow() {
        if (borrowed) {
            System.out.println("This book has already been borrowed.");
        } else {
            borrowed = true;
            System.out.println("Successfully borrowed " + title);
        }
    }

    public void returnBook() {
        if (borrowed) {
            borrowed = false;
            System.out.println("Successfully returned " + title);
        } else {
            System.out.println("This book has not been borrowed yet.");
        }
    }
}
 class Person {
    private String name;
    private int age;
    private String gender;

    public Person(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void eat() {
        System.out.println(name + " is eating.");
    }

    public void sleep() {
        System.out.println(name + " is sleeping.");
    }
}

 class Car {
    private String brand;
    private String model;
    private int year;

    public Car(String brand, String model, int year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    public String getBrand() {
        return brand;
    }

    public String getModel() {
        return model;
    }

    public int getYear() {
        return year;
    }

    public void displayInfo() {
        System.out.println("Car: " + brand + " " + model + " (" + year + ")");
    }
}


class Student {
    private String name;
    private int age;
    private String major;

    public Student(String name, int age, String major) {
        this.name = name;
        this.age = age;
        this.major = major;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getMajor() {
        return major;
    }

    public void displayInfo() {
        System.out.println(name + " - Age: " + age + " - Major: " + major);
    }
}
View Code

代码分析:

1.菜品类:对应菜谱上一道普通菜的信息。

2.菜谱类:对应菜谱,包含饭店提供的所有菜的信息。

3.点菜记录类:保存订单上的一道菜品记录。

4.订单类:保存用户点的所有菜的信息。

5.Table类:保留桌号,时间等信息,从而计算各桌总价。

这些是菜单4用到的类,菜单5还用了以下的类:

6.SpecialDish类:对普通菜系做了一个继承的关系,对应菜谱上特色菜的信息。

7.lastPrint类:打印出每桌菜的口味以及每道菜的价格,最后计算出总价。

这段代码是一个简单的餐厅点餐系统的Java实现。它包括了菜单管理、桌号管理、订单记录等功能。我会逐步解释一下主要的组成部分和功能:

  1. 主要功能:

    • 代码中定义了一个名为Main的主类,其中包含了main方法作为程序的入口点。
    • 程序通过读取用户的输入来执行相应的操作,比如添加菜品、点餐、结账等。
  2. 数据结构:

    • 程序中使用了多个自定义的类来表示不同的概念,比如DishSpecialDishTableRecordPersonPay等,用于表示菜品、特色菜品、桌号、订单记录、支付记录等。
    • 使用数组和ArrayList来存储这些对象,比如dishesspecialDishestablesrecordspersonPays等。
  3. 功能实现:

    • 程序通过读取用户输入的命令来执行相应的操作,比如添加新的菜品、记录顾客点菜情况、结账等。
    • 对用户输入的格式进行了正则表达式匹配,以确保输入的命令符合特定的格式要求。
  4. 存在问题:

    • 代码中存在一些硬编码,比如数组长度的固定值、部分变量命名不够清晰等,可能会限制程序的扩展性和可维护性。
    • 部分功能实现的逻辑比较复杂,可读性不佳。

总的来说,这段代码实现了简单的餐厅点餐系统的功能,但仍然有改进的空间,比如提高代码的可读性、优化数据结构的设计、封装更多的功能模块等。

4.期中考试:

 测验1-圆类设计

创建一个圆形类(Circle),私有属性为圆的半径,从控制台输入圆的半径,输出圆的面积

输入格式:

输入圆的半径,取值范围为(0,+∞),输入数据非法,则程序输出Wrong Format,注意:只考虑从控制台输入数值的情况

输出格式:

输出圆的面积(保留两位小数,可以使用String.format(“%.2f”,输出数值)控制精度)

 

测验2-类结构设计

设计一个矩形类,其属性由矩形左上角坐标点(x1,y1)及右下角坐标点(x2,y2)组成,其中,坐标点属性包括该坐标点的X轴及Y轴的坐标值(实型数),求得该矩形的面积。类设计如下图:


image.png

输入格式:

分别输入两个坐标点的坐标值x1,y1,x2,y2。

输出格式:

输出该矩形的面积值(保留两位小数)。

 

测验3-继承与多态

将测验1与测验2的类设计进行合并设计,抽象出Shape父类(抽象类),Circle及Rectangle作为子类,类图如下所示:


image.png

import java.util.*;
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 radius2 = input.nextDouble();
            Shape circle = new Circle(radius2);
            double mj = circle.getArea();
            System.out.printf("%.2f%n", mj);

            break;
        case 2://Rectangle
            double x1 = input.nextDouble();
            double y1 = input.nextDouble();
            double x2 = input.nextDouble();
            double y2 = input.nextDouble();

            Shape point = new Rectangle(x1, y1, x2, y2);
            double width = x2 - x1;
            double height = y2 - y1;
            //double mj =width * height;
            System.out.printf("%.2f%n", width * height);


            break;
    }
}
        }

     abstract class Shape {
        public abstract double getArea();
    }

    // Circle 类
     class Circle extends Shape {
        private double radius;

        public Circle(double radius) {
            this.radius = radius;
        }

        @Override
        public double getArea() {
            return Math.PI * radius * radius;
        }
    }

    // Rectangle 类
     class Rectangle extends Shape {
        private double x1, y1, x2, y2;

        public Rectangle(double x1, double y1, double x2, double y2) {
            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;
        }


        @Override
        public double getArea() {
            double width = x2 - x1;
            double height = y2 - y1;
            return width * height;
        }
    }
View Code

测验4-抽象类与接口

该题目在测验3的题目基础上,重构类设计,实现列表内图形的排序功能(按照图形的面积进行排序)。
提示:题目中Shape类要实现Comparable接口。

而且此题目还有特殊的输入格式:

输入格式:

输入图形类型(1:圆形;2:矩形;0:结束输入)

输入图形所需参数

输出格式:

按升序排序输出列表中各图形的面积(保留两位小数),各图形面积之间用空格分隔。

 

踩坑心得:

PTA4:菜单3:菜单计价程序系列是从易到难的迭代性题型,需要得到重视,比如我,就是一开始由于菜单1,2没有完全写出来,然后便影响到了菜单3,再加上当时java还处于刚刚起步的阶段,一时之间便耽搁了很长时间,不过在后面我总算是意识到了菜单题目的重要性,在写4,5的时候情况好了好多。

PTA5:菜单4:1.对正则表达式的理解还不够清晰,而菜单计价程序在这里已经用到了许多正则表达式的方法,因此我们要小心;2.菜单4比3增加了许多的异常情况,其中还涉及到了一个排序的问题,因此我们需要的不同的排序算法有个较为清晰的了解,防止顺序不对还有一些出错的情况;3.在增加了特色菜的情况下,最后每一桌计算总价的方式发生了改变,如何用比较简洁且直观的方式计算就成了我们的问题。

PTA6:菜单5:1.这里比4的特色菜增加了一个口味度的描述,乍一看,好像只是多了一个东西,但这一个东西造成了很大的改变,也无形中增加了很多内容,所以在这里,我们需要把普通菜和特色菜进行一个类的划分,更加方便观看,但是也促进了更多代码上的变化;2.要注意,最后不仅仅是在计算总价时需要考虑代点菜桌上所有菜的价格,在计算口味度平均值时同样需要考虑到代点菜桌上所有特色菜的口味度。

期中考试:继承和多态是Java程序设计的重要特性,它们能够有效地组织和管理复杂的代码结构,并使代码具有更高的可重用性和可扩展性

 改进建议:

这个餐厅点餐系统的代码已经很不错了,但是还有一些地方可以改进。以下是一些建议:

  1. 使用面向对象的设计:

    • 可以更多地利用面向对象的特性,比如封装、继承和多态,来简化代码并提高可维护性。
  2. 动态数据结构:

    • 考虑使用动态数据结构,比如HashMap或者LinkedHashMap来存储菜品、桌号等信息,这样可以更好地应对不确定数量的数据。
  3. 异常处理:

    • 在用户输入和其他操作中加入异常处理,以增强程序的稳定性。
  4. 模块化和重构:

    • 将功能模块化,将相似功能的代码提取成方法,并考虑进行代码重构以提高代码的清晰度和可读性。
  5. 单一职责原则:

    • 确保每个类和方法只负责一项功能,遵循单一职责原则,以提高代码的灵活性和可维护性。
  6. 单元测试:

    • 编写单元测试,确保每个模块的功能正确性,减少潜在的bug。
  7. 界面优化:

    • 如果是一个带有用户界面的点餐系统,可以考虑优化用户交互界面,使其更加友好和直观。
  8. 注释和文档:

    • 添加详细的注释,以解释代码的含义和逻辑,同时编写文档以便其他开发人员理解系统架构和功能。

通过应用这些改进建议,可以使代码更加健壮、可扩展和易于维护。

总结:
   对于这个餐厅点餐系统的Java代码,改进的建议包括使用面向对象的设计、使用动态数据结构、加强异常处理、模块化和重构、遵循单一职责原则、编写单元测试、优化用户界面、添加注释和文档等方面。通过这些改进,可以提高代码的可维护性、健壮性和扩展性,使系统更加稳定和易于开发和维护。从中我还学到了

 

  1. 面向对象设计的重要性:了解了如何更好地利用面向对象的特性来提高代码的可维护性和灵活性。

  2. 系统架构方面的知识:学习了如何设计动态数据结构、异常处理、模块化和重构等方面的技巧,以构建更健壮的系统。

  3. 软件开发中的最佳实践:了解了单一职责原则、单元测试、界面优化、日志记录等在软件开发中的重要性和应用方法。

  4. 安全和性能考虑:意识到了系统安全性和性能优化在实际开发中的必要性,以及相关的具体实施方法。