题目集4,5及期中考试

HT-snocle / 2023-07-01 / 原文

前言:题目集4涉及到了面向对象编程中与面向过程不同的特殊语法:类与对象中所要用到的为对象定义类,使用构造方法构造对象,通过引用变量引用对象,对象数组等语法知识,对其基本使用能力进行考察,题量适中,难度不易;期中考试涉及到了java中较为基础和较为复杂的语法知识,包含但不限于输入输出中所要用到的java.util.Scanner包,Scanner input = new Scanner(System.in),System.out.println语句、选择判断中所要用到的if/else,else if,switch语句、循环中所要用到的while,do while,for,foreach语句的语法知识,题量适中,难度较为困难;题目集5基于题目集4进一步深入,虽没有较多新知识点的考察,但更能考察我们对较为复杂的需求的处理方法,题量适中,难度较高。总而言之,难度层层递增,对我们的代码水平要求逐渐提升,让我们的编程思维一步步变得更完善。以下对这三次题目集进行分析:

题目集4:

  (1)7-1 菜单计价程序-4:

  为了读者能够更好的了解此代码,下面将对题目进行详细阐述:

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

输入内容按先后顺序包括两部分:菜单、订单,最后以"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"。
  代码如下:

import java.time.YearMonth;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Menu menu = new Menu();
        Table[] tablemes = new Table[57];
        int j = 0;
        int l = 0;
        int cntTab = 0;
        String[] temp;
        int tempordernum = 0;
        String input;
        String regex = "[\\u4e00-\\u9fa5]* \\d*";
        String regex1 = "[\\u4e00-\\u9fa5]* \\d* T";
        String regex2 = "\\d (delete)";
        String regex3 = "(table) ([1-4][0-9]*|5[0-5]*) \\d{4}/\\d+/\\d{1,2} ([0-1]?[0-9]|2[0-3])/([0-5][0-9])/([0-5][0-9])";
        String regex4 = "([1-9]|[1-9][0-9]*) [\\u4e00-\\u9fa5]+ \\d+ \\d+";
        String regex5 = "([1-4][0-9]*|5[0-5]*|[1-9]) \\d [\\u4e00-\\u9fa5]+ [123] (1[0-5]|[1-9])";

        while (true) {
            int count;
            input = sc.nextLine();
            if(input.equals("end"))
                break;
            if(input.equals("")) {
                System.out.println("wrong format");
                continue;
            }
            temp = input.split(" ");
            count = temp.length;
            if(count==2){
                if(input.matches(regex2)){
                    if (tablemes[cntTab] == null) throw new AssertionError();
                    if(tablemes[cntTab].inputIsvalid){
                        tablemes[cntTab].order.delARecordByOrderNum(Integer.parseInt(temp[0]));

                    }
                }else if(input.matches(regex)){
                    if (cntTab == 0) {
                        menu.dishes[j] = new Dish();
                        menu.dishes[j] = menu.addDish(temp[0], Integer.parseInt(temp[1]));
                        j++;
                    } else if(tablemes[cntTab].inputIsvalid){
                        System.out.println("invalid dish");
                    }

                }else {
                    System.out.println("wrong format");
                }
            }else if(count==3){
                if(input.matches(regex1)) {
                    if(cntTab!=0) {
                        if(tablemes[cntTab].inputIsvalid)
                            System.out.println("invalid dish");
                        else
                            continue;
                    }

                    menu.dishes[j] = new Dish();
                    menu.dishes[j] = menu.addDish(temp[0], Integer.parseInt(temp[1]));
                    menu.dishes[j].isSpecial = true;
                    j++;
                }else
                    System.out.println("wrong format");
            }
            else if(temp[0].equals("table")||input.contains("/")) {
                cntTab++;
                tablemes[cntTab] = new Table();
                if(temp[0].equals("table")){
                    if(input.matches(regex3))
                        tablemes[cntTab].AheadProcess(input);
                    tablemes[cntTab].inputIsvalid=true;
                    if (input.matches(regex3)) {
                        if(true){
                            System.out.println(tablemes[cntTab].tableNum+" date error");
                            tablemes[cntTab].inputIsvalid=false;
                            continue;
                        }
                        if(true){
                            tablemes[cntTab].inputIsvalid=false;
                            continue;
                        }
                        for(int i =1;i<cntTab;i++){
                            if (tablemes[i].inputIsvalid && tablemes[cntTab].CheckSameTime(tablemes[i])) {
                                tablemes[cntTab].istoSum = true;
                            } else {
                                l = 0;
                            }
                            tempordernum = 0;
                        }
                        if(tablemes[cntTab].discnt>0)
                            System.out.println("table " + tablemes[cntTab].tableNum + ": ");
                        else {
                            System.out.println("table " + tablemes[cntTab].tableNum + " out of opening hours");
                            tablemes[cntTab].inputIsvalid = false;
                        }
                        continue;
                    } else {
                        tablemes[cntTab].inputIsvalid = false;
                        if(!temp[1].equals("")&&temp[1].charAt(0)>='1'&&temp[1].charAt(0)<='9'&&!temp[1].contains("/")){
                            if(Integer.parseInt(temp[1])<1||Integer.parseInt(temp[1])>55){
                                System.out.println(Integer.parseInt(temp[1])+" table num out of range");
                                continue;
                            }
                        }
                    }
                }
                System.out.println("wrong format");
                tablemes[cntTab].inputIsvalid = false;
                if(!temp[0].equals("table"))
                    tablemes[cntTab].istoSum = true;

            }else if(count==4){
                if(input.matches(regex4)&&(Objects.requireNonNull(tablemes[cntTab]).inputIsvalid||tablemes[cntTab].istoSum)){
                    Dish tem;
                    int aheadcntTab = cntTab-1;
                    if(!tablemes[cntTab].istoSum) {
                        tablemes[cntTab].order.records[l] = new Record();
                        tablemes[cntTab].order.records[l] = tablemes[cntTab].order.addARecord(Integer.parseInt(temp[0]), temp[1], Integer.parseInt(temp[2]), Integer.parseInt(temp[3]));
                        if(l-1>=0){
                            tempordernum = getTempordernum(tablemes, l, temp, tempordernum, cntTab);
                        }else {
                            if(tablemes[cntTab].order.records[l].Checkahead())
                                tempordernum = tablemes[cntTab].order.records[l].orderNum;
                        }
                        if((tem = menu.searchDish(temp[1]))!=null){
                            float temdiscnt;
                            tablemes[cntTab].order.records[l].d = tem;
                            temdiscnt = tablemes[cntTab].order.records[l].Checkportion(tablemes[cntTab].discnt);
                            if(temdiscnt!=1F)
                                tablemes[cntTab].rediscnt = temdiscnt;
                            if(tablemes[cntTab].order.records[l].exist==1&&tablemes[cntTab].order.records[l].noNeed) {
                                if(tablemes[cntTab].rediscnt!=1) {
                                    tablemes[cntTab].sum += Math.round(tablemes[cntTab].order.records[l].getPrice() * tablemes[cntTab].rediscnt);
                                    tablemes[cntTab].rediscnt=1.0F;
                                }
                                else
                                    tablemes[cntTab].sum += Math.round(tablemes[cntTab].order.records[l].getPrice() * tablemes[cntTab].discnt);
                            }
                        }

                        if(!tablemes[cntTab].istoSum){
                            l++;
                        }
                    } else{
                        tablemes[aheadcntTab].order.records[l] = new Record();
                        tablemes[aheadcntTab].order.records[l] = tablemes[aheadcntTab].order.addARecord(Integer.parseInt(temp[0]), temp[1], Integer.parseInt(temp[2]), Integer.parseInt(temp[3]));
                        if(l-1>=0){
                            tempordernum = getTempordernum(tablemes, l, temp, tempordernum, aheadcntTab);
                        }
                        if((tem = menu.searchDish(temp[1]))!=null){
                            float temdiscnt;
                            tablemes[aheadcntTab].order.records[l].d = tem;
                            temdiscnt = tablemes[aheadcntTab].order.records[l].Checkportion(tablemes[aheadcntTab].discnt);
                            if(temdiscnt==0.7F)
                                tablemes[aheadcntTab].rediscnt = temdiscnt;
                            if(tablemes[aheadcntTab].order.records[l].exist==1) {
                                if(tablemes[aheadcntTab].rediscnt!=1) {
                                    tablemes[aheadcntTab].sum += Math.round(tablemes[aheadcntTab].order.records[l].getPrice() * tablemes[aheadcntTab].rediscnt);
                                    tablemes[aheadcntTab].rediscnt=1.0F;
                                }
                                else
                                    tablemes[aheadcntTab].sum += Math.round(tablemes[aheadcntTab].order.records[l].getPrice() * tablemes[cntTab].discnt)-1;
                            }
                        }

                        l++;
                    }

                }else {
                    if(tablemes[cntTab]==null) {
                        System.out.println("wrong format");
                        continue;
                    }
                    if(tablemes[cntTab]!=null&&tablemes[cntTab].inputIsvalid)
                        System.out.println("wrong format");
                }
            }
            else if(count==5&& Objects.requireNonNull(tablemes[cntTab]).inputIsvalid){
                int temSum = 0;
                if(input.matches(regex5)){
                    int AnothNum = Integer.parseInt(temp[0]);
                    tablemes[cntTab].order.records[l] = tablemes[cntTab].order.takeorderfor(tablemes[cntTab].tableNum,tablemes,AnothNum,Integer.parseInt(temp[1]),temp[2],Integer.parseInt(temp[3]),Integer.parseInt(temp[4]));
                    Dish tem;
                    if((tem = menu.searchDish(temp[2]))!=null&&tablemes[cntTab].order.records[l]!=null){
                        tablemes[cntTab].order.records[l].isTaked = true;
                        float temdiscnt;
                        tablemes[cntTab].order.records[l].d = tem;
                        temdiscnt = tablemes[cntTab].order.records[l].Checkportion(tablemes[cntTab].discnt);
                        if(temdiscnt!=1F)
                            tablemes[cntTab].rediscnt = temdiscnt;
                        if(tablemes[cntTab].order.records[l].exist==1&&tablemes[cntTab].order.records[l].noNeed) {
                            if(tablemes[cntTab].rediscnt!=1) {
                                tablemes[cntTab].sum += Math.round((temSum=tablemes[cntTab].order.records[l].getPrice()) * tablemes[cntTab].rediscnt);
                                tablemes[cntTab].rediscnt=1.0F;
                            }
                            else
                                tablemes[cntTab].sum +=  Math.round((temSum =tablemes[cntTab].order.records[l].getPrice()) * tablemes[cntTab].discnt);
                        }
                        System.out.println(temp[1] + " table " + tablemes[cntTab].tableNum + " pay for table " + temp[0] + " " + temSum);
                    }
                    if(tablemes[cntTab].order.records[l]!=null)
                        l++;
                }else
                    System.out.println("wrong format");

            }else{
                assert tablemes[cntTab] != null;
                if(tablemes[cntTab].inputIsvalid)
                    System.out.println("wrong format");
            }
        }
        for(int i=1;i<=cntTab;i++){
            if(tablemes[i].inputIsvalid&&!tablemes[i].istoSum)
                tablemes[i].GetTotalPrice();
        }

    }

    private static int getTempordernum(Table[] tablemes, int l, String[] temp, int tempordernum, int aheadcntTab) {
        if(Integer.parseInt(temp[0])<=tempordernum) {
            System.out.println("record serial number sequence error");
            tablemes[aheadcntTab].order.records[l].exist=0;
        }else
        if(tablemes[aheadcntTab].order.records[l]!=null&&tablemes[aheadcntTab].order.records[l].noNeed)
            tempordernum = tablemes[aheadcntTab].order.records[l].orderNum;
        return tempordernum;
    }
}


class Dish {
    String name;
    boolean isSpecial = false;
    int unit_price;
    boolean exist = true;

    int getPrice(int portion) {
        int price0;
        switch (portion) {
            case 1:
                price0 = unit_price;
                break;
            case 2:
                price0 = Math.round((float) (unit_price * 1.5));
                break;
            case 3:
                price0 = unit_price * 2;
                break;
            default:
                throw new IllegalArgumentException("Invalid portion: " + portion);
        }
        return price0;
    }

    public Dish() {
    }

    public String getName() {
        return name;
    }

    public int getUnit_price() {
        return unit_price;
    }

    public void setUnit_price(int unit_price) {
        this.unit_price = unit_price;
    }

    public boolean isExist() {
        return exist;
    }

    public void setExist(boolean exist) {
        this.exist = exist;
    }
}

class Menu {
    Dish[] dishes = new Dish[10];
    int count = 0;
    Dish searchDish(String dishName) {
        for (int i = 0; i < count; i++) {
            Dish dish = dishes[i];
            if (dishName.equals(dish.name) && dish.exist) {
                return dish;
            }
        }
        System.out.println(dishName + " does not exist");
        return null;
    }

    Dish addDish(String dishName, int unitPrice) {
        if (unitPrice < 1 || unitPrice > 300) {
            System.out.println(dishName + " price out of range " + unitPrice);
            return null;
        }
        Dish dish = new Dish();
        dish.name = dishName;
        dish.unit_price = unitPrice;
        dishes[count++] = dish;
        return dish;
    }
}

class Order {
    Record[] records = new Record[100];
    private int count = 0;

    public int getTotalPrice() {
        int sum = 0;
        for (int i = 0; i < count; i++) {
            Record record = records[i];
            if (record != null && record.exist == 1) {
                sum += record.getPrice();
            }
        }
        return sum;
    }

    public Record addARecord(int orderNum, String dishName, int portion, int num) {
        int index = -1;
        for (int i = 0; i < count; i++) {
            Record record = records[i];
            if (record != null && record.d.name.equals(dishName) && record.portion == portion) {
                index = i;
                break;
            }
        }
        if (index == -1) {
            Record record = new Record();
            record.d.name = dishName;
            record.orderNum = orderNum;
            record.portion = portion;
            record.num = num;
            records[count++] = record;
            return record;
        } else {
            return records[index];
        }
    }

    public Record takeorderfor(int mynum, Table[] tables, int anotherNum, int orderNum, String dishName, int portion, int num) {
        boolean flag = false;
        for (Table table : tables) {
            if (table != null && table.tableNum != mynum && table.tableNum == anotherNum) {
                flag = true;
                break;
            }
        }
        if (flag) {
            return addARecord(orderNum, dishName, portion, num);
        } else {
            System.out.println("Table number: " + anotherNum + " does not exist");
            return null;
        }
    }

    public static boolean checkDateFormat(String tempDate) {

        if (tempDate.length() != 10 ){
            return false;
        }
        for (int i = 0; i < 4; i++) {
            if (tempDate.charAt(i) > 57 || tempDate.charAt(i) < 48) {
                return false;
            }
        }
        if (tempDate.charAt(5) > 57 || tempDate.charAt(5) < 48 || tempDate.charAt(6) > 57 || tempDate.charAt(6) < 48) {
            return false;
        }
        if (tempDate.charAt(8) > 57 || tempDate.charAt(8) < 48 || tempDate.charAt(9) > 57 || tempDate.charAt(9) < 48) {
            return false;
        }
        if (tempDate.charAt(7) !=45 || tempDate.charAt(4) !=45) {
            return false;
        }
        if (tempDate.charAt(5) > 49 || (tempDate.charAt(5) == 49 && tempDate.charAt(6) > 50)) {
            return false;
        }
        if (tempDate.charAt(8) > 51 || (tempDate.charAt(8) == 51 && tempDate.charAt(9) > 49)) {
            return false;
        }
        return true;
    }

    public static boolean checkSpecialDate(int[] arrayTemp) {

        if (arrayTemp[1] == 2 && arrayTemp[2] > 29) {
            return false;
        }
        if (arrayTemp[1] < 8) {
            if (arrayTemp[1] % 2 == 0 && arrayTemp[2] > 30) {return false;}
        }
        if (arrayTemp[1] > 7) {
            if (arrayTemp[1] % 2 == 1 && arrayTemp[2] > 30) {return false;}
        }
        if (arrayTemp[0] % 4 != 0 || (arrayTemp[0] % 100 == 0 && arrayTemp[0] % 400 != 0)) {
            if (arrayTemp[1] == 2 && arrayTemp[2] > 28) {return false;}
        }
        return true;
    }

    public void delARecordByOrderNum(int orderNum) {
        if (orderNum > count || orderNum <= 0) {
            System.out.println("Delete error");
            return;
        }
        Record record = records[orderNum - 1];
        if (record.exist == 0) {
            System.out.println("Deduplication " + orderNum);
            return;
        }
        record.exist = 0;
    }
}

class Record {
    int orderNum;
    Dish d = new Dish();
    int num = 0;
    int portion;
    boolean noNeed = true;
    int exist = 1;
    float realDiscount = 1;
    boolean isTaked = false;

    int getPrice() {
        return Math.round(d.getPrice(portion) * num);
    }

    float Checkportion(float discount) {
        if (portion < 1 || portion > 3) {
            System.out.println(orderNum + " portion out of range " + portion);
            exist = 0;
            noNeed = false;
        } else if (num < 1 || num > 15) {
            System.out.println(orderNum + " num out of range " + num);
            exist = 0;
            noNeed = false;
        } else {
            if (d.isSpecial && (discount == 0.8F || discount == 0.6F)) {
                realDiscount = 0.7F;
            }
            if (exist == 1 && !isTaked) {
                System.out.println(orderNum + " " + d.name + " " + getPrice());
            }
        }
        return realDiscount;
    }

    boolean Checkahead() {
        return num >= 1 && num <= 15 && portion >= 1 && portion <= 3;
    }
}

class Table {
    int tableNum;
    boolean inputIsvalid = false;
    boolean istoSum = false;
    String tableDtime;
    int year, month, day, week, hh, mm, ss;
    int sum = 0;
    int primesum = 0;
    Order order = new Order();
    float discnt = -1;
    float rediscnt = 1;
    void GetTotalPrice() {
        if (discnt > 0) {
            primesum = order.getTotalPrice();
            if (primesum == 0)
                sum = 0;
            System.out.println("table " + tableNum + ": " + primesum + " " + sum);
        }
    }

    void AheadProcess(String tableDtime) {
        this.tableDtime = tableDtime;
        processTime();
        discount();
    }

    void processTime() {
        String[] temp = tableDtime.split(" ");
        tableNum = Integer.parseInt(temp[1]);
        String[] temp1 = temp[2].split("/");
        String[] temp2 = temp[3].split("/");

        year = Integer.parseInt(temp1[0]);
        month = Integer.parseInt(temp1[1]);
        day = Integer.parseInt(temp1[2]);

        Calendar c = Calendar.getInstance();
        c.set(year, (month - 1), day);
        week = c.get(Calendar.DAY_OF_WEEK);
        if (week == 1)
            week = 7;
        else
            week--;

        hh = Integer.parseInt(temp2[0]);
        mm = Integer.parseInt(temp2[1]);
        ss = Integer.parseInt(temp2[2]);
    }



    void discount() {
        if (week >= 1 && week <= 5) {
            if (hh >= 17 && hh < 20 || (hh == 20 && mm < 30)) {
                discnt = 0.8F;
            } else if ((hh >= 11 && hh <= 13) || (hh == 10 && mm >= 30) || (hh == 14 && mm < 30)) {
                discnt = 0.6F;
            } else {
                discnt = 1.0F;
            }
        } else {
            if (hh >= 10 && hh <= 20 || (hh == 9 && mm >= 30) || (hh == 21 && mm < 30)) {
                discnt = 1.0F;
            } else {
                discnt = 1.0F;
            }
        }
    }

    boolean CheckSameTime(Table table) {

        return false;
    }
}

本题基于上一次点菜计价问题进一步深入探究,对类,对象,循环,数组的知识点均有考察,是一道综合性较强的问题。做题思路:利用while循环,以end为结束标志符实现可控制范围输入,利用对象数组DishType存储数据,引入一个标志变量flag以判断语句处理数据并进行输出。对我们各种情况的剥析能力要求更高。以下为各个类的功能示意,可供参考:

菜品类:对应菜谱上一道菜的信息。
Dish {
String name;//菜品名称
int unit_price; //单价
int getPrice(int portion)//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份)
}

菜谱类:对应菜谱,包含饭店提供的所有菜的信息。
Menu {
Dish[] dishs ;//菜品数组,保存所有菜品信息
Dish searthDish(String dishName)//根据菜名在菜谱中查找菜品信息,返回Dish对象。
}

点菜记录类:保存订单上的一道菜品记录
Record {
Dish d;//菜品
int portion;//份额(1/2/3代表小/中/大份)
int getPrice()//计价,计算本条记录的价格
}

订单类:保存用户点的所有菜的信息。
Order {
Record[] records;//保存订单上每一道的记录
int getTotalPrice()//计算订单的总价
Record addARecord(String dishName,int portion)
//添加一条菜品信息到订单中。
}

以下为类图:

 

以下为测试结果:

期中考试:

  (1)7-1 测验1-圆类设计:

  代码如下:

import java.util.Scanner;

public class Circle {
    private double radius;

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

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

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double radius = scanner.nextDouble();

        if (radius > 0) {
            Circle circle = new Circle(radius);
            double area = circle.getArea();
            System.out.println(String.format("%.2f", area));
        } else {
            System.out.println("Wrong Format");
        }

        scanner.close();
    }
}

本题思路:这段代码首先创建了一个Circle类,私有属性为圆的半径。在构造方法中,将输入的半径赋值给私有属性radius。接下来,代码定义了一个getArea方法,用于计算圆的面积。在main方法中,首先使用Scanner类从控制台获取输入的半径值,然后判断半径是否合法(大于0)。如果半径合法,则创建Circle对象并调用getArea方法计算面积,并使用String.format("%.2f", area)控制输出的精度为两位小数。如果半径不合法,则输出"Wrong Format"。

以下为测试结果:

  (2)7-2 测验2-类结构设计:

  代码如下:

import java.util.Scanner;

public class Rectangle {
    private double x1;
    private double y1;
    private double x2;
    private double y2;

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

    public double getArea() {
        double width = Math.abs(x2 - x1);
        double height = Math.abs(y2 - y1);
        return width * height;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double x1 = scanner.nextDouble();
        double y1 = scanner.nextDouble();
        double x2 = scanner.nextDouble();
        double y2 = scanner.nextDouble();

        Rectangle rectangle = new Rectangle(x1, y1, x2, y2);
        double area = rectangle.getArea();
        System.out.println(String.format("%.2f", area));

        scanner.close();
    }
}

本题思路:这段代码首先创建了一个Rectangle类,属性包括矩形的左上角坐标点(x1,y1)和右下角坐标点(x2,y2)。在构造方法中,将输入的坐标值赋值给对应的属性。接下来,代码定义了一个getArea方法,用于计算矩形的面积。在main方法中,使用Scanner类从控制台获取输入的坐标点的坐标值,并创建Rectangle对象。然后,调用getArea方法计算面积,并使用String.format("%.2f", area)控制输出的精度为两位小数。

以下为测试结果:

  (3)7-3 测验3-继承与多态:

  代码如下:

import java.util.*;

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

class Rectangle extends Shape {
    double x1;
    double x2;
    double y1;
    double y2;
    double areaRectangle;

    @Override
    public double getArea() {
        return areaRectangle;
    }
}

class Circle extends Shape {
    double radius;

    @Override
    public double getArea() {
        double area = 0;
        if (radius > 0) {
            area = radius * radius * 3.1415926535;
        }
        return area;
    }
}

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 circle = new Circle();
                circle.radius = input.nextDouble();
                if (circle.radius > 0) {
                    System.out.printf("%.2f", circle.getArea());
                } else {
                    System.out.println("Wrong Format");
                }
                break;
            case 2:
                Rectangle rectangle = new Rectangle();
                rectangle.x1 = input.nextDouble();
                if (false) {
                }
                rectangle.y1 = input.nextDouble();
                if (false) {
                }
                rectangle.x2 = input.nextDouble();
                if (false) {
                }
                rectangle.y2 = input.nextDouble();
                rectangle.areaRectangle = (rectangle.x1 - rectangle.x2) * (rectangle.y1 - rectangle.y2);
                if (rectangle.areaRectangle < 0) {
                    System.out.printf("%.2f", -rectangle.getArea());
                } else if (rectangle.getArea() > 0) {
                    System.out.printf("%.2f", rectangle.getArea());
                } else {
                    System.out.println("0.00");
                }
                break;
            default:
        }
    }
}

本题将上面两题结合,这里不进行过多阐述。

以下为测试结果:

  (4)7-4 测验4-抽象类与接口:

  代码如下:

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ArrayList<Shape> list = new ArrayList<>();

        int choice = input.nextInt();

        while (choice != 0) {
            switch (choice) {
                case 1:
                    double radiums = input.nextDouble();
                    Shape circle = new Circle(radiums);
                    list.add(circle);
                    break;
                case 2:
                    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()) + " ");
        }
    }
    static void printArea(Shape shape) {
        double f = shape.getArea();
        if (shape instanceof Circle) {
            if (f <= 0)
                System.out.print("Wrong Format");
            else {
                String tmp = String.format("%.2f", f);
                System.out.print(tmp);
            }
        } else {
            String tmp = String.format("%.2f", f);
            System.out.print(tmp);
        }
    }

}

class Point {
    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;
    }

    double x, y;

}

class Rectangle extends Shape {
    public Rectangle(Point topLeftPoint, Point lowerRightPoint) {
        super();
        this.topLeftPoint = topLeftPoint;
        this.lowerRightPoint = lowerRightPoint;
    }

    public Point getTopLeftPoint() {
        return topLeftPoint;
    }

    public void setTopLeftPoint(Point topLeftPoint) {
        this.topLeftPoint = topLeftPoint;
    }

    public Point getLowerRightPoint() {
        return lowerRightPoint;
    }

    public void setLowerRightPoint(Point lowerRightPoint) {
        this.lowerRightPoint = lowerRightPoint;
    }

    Point topLeftPoint;
    Point lowerRightPoint;

    double getLength() {
        return Math.abs(topLeftPoint.x - lowerRightPoint.x);

    }

    double getHeight() {
        return Math.abs(topLeftPoint.y - lowerRightPoint.y);
    }

    public static boolean checkDateFormat(String tempDate) {

        if (tempDate.length() != 10 ){
            return false;
        }
        for (int i = 0; i < 4; i++) {
            if (tempDate.charAt(i) > 57 || tempDate.charAt(i) < 48) {
                return false;
            }
        }
        if (tempDate.charAt(5) > 57 || tempDate.charAt(5) < 48 || tempDate.charAt(6) > 57 || tempDate.charAt(6) < 48) {
            return false;
        }
        if (tempDate.charAt(8) > 57 || tempDate.charAt(8) < 48 || tempDate.charAt(9) > 57 || tempDate.charAt(9) < 48) {
            return false;
        }
        if (tempDate.charAt(7) !=45 || tempDate.charAt(4) !=45) {
            return false;
        }
        if (tempDate.charAt(5) > 49 || (tempDate.charAt(5) == 49 && tempDate.charAt(6) > 50)) {
            return false;
        }
        if (tempDate.charAt(8) > 51 || (tempDate.charAt(8) == 51 && tempDate.charAt(9) > 49)) {
            return false;
        }
        return true;
    }

    public static boolean checkSpecialDate(int[] arrayTemp) {

        if (arrayTemp[1] == 2 && arrayTemp[2] > 29) {
            return false;
        }
        if (arrayTemp[1] < 8) {
            if (arrayTemp[1] % 2 == 0 && arrayTemp[2] > 30) {return false;}
        }
        if (arrayTemp[1] > 7) {
            if (arrayTemp[1] % 2 == 1 && arrayTemp[2] > 30) {return false;}
        }
        if (arrayTemp[0] % 4 != 0 || (arrayTemp[0] % 100 == 0 && arrayTemp[0] % 400 != 0)) {
            if (arrayTemp[1] == 2 && arrayTemp[2] > 28) {return false;}
        }
        return true;
    }

    public double getArea() {
        return getLength() * getHeight();
    }

}


class Shape implements Comparable<Shape> {
    public Shape() {

    }

    public double getArea() {
        return 0;
    }

    public int compareTo(Shape shape) {
        double s1, s2;
        s1 = getArea();
        s2 = shape.getArea();
        if (s1 > s2)
            return 1;
        else if (s1 < s2)
            return -1;
        return 0;
    }
}

class Circle extends Shape {
    double radius;

    Circle(double r) {
        radius = r;
    }

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

}

以下为该题的分析:

  1. 创建了一个Shape抽象类作为所有形状的父类,它包含了一个抽象方法getArea()用于计算形状的面积,以及一个compareTo()方法用于比较两个形状的面积大小。

  2. 创建了一个Circle类,继承自Shape类,用于表示圆形。它包含一个radius属性表示圆的半径,以及一个getArea()方法用于计算圆形的面积。

  3. 创建了一个Point类,用于表示坐标点,包含x和y两个属性。

  4. 创建了一个Rectangle类,继承自Shape类,用于表示矩形。它包含一个topLeftPoint属性表示矩形的左上角坐标点,以及一个lowerRightPoint属性表示矩形的右下角坐标点。它还包含getLength()和getHeight()方法用于计算矩形的长度和宽度,以及getArea()方法用于计算矩形的面积。

  5. 在Main类的main方法中,使用Scanner类从控制台读取输入,根据输入的选择创建Circle或Rectangle对象,并将它们添加到一个ArrayList中。然后,根据ArrayList的元素使用Comparator进行排序,并通过调用getArea()方法获取形状的面积并输出。

以下为测试结果:

题目集5:

  (1)7-1 菜单计价程序-5:

  代码如下:

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 boolean searchCall(String threeCall) {
        String []CallNumber=new String[]{"180","181","189","133","135","136"};
        for(int i=0;i<CallNumber.length;i++)
            if(CallNumber[i].equals(threeCall))return false;
        return true;
    }
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");
        Menu menu = new Menu();
        HashMap<String ,String>hash=new HashMap<>();
        String []customer=new String[30];
        int cnt=0;
        int nm=0;
        ArrayList<Table> tables = new ArrayList<Table>();
        Scanner input = new Scanner(System.in);
        String []zhe=new String[]{"不甜","微甜","稍甜","甜"};
        String []jin=new String[]{"不酸","微酸","稍酸","酸","很酸"};
        String []chuan=new String[]{"不辣","微辣","稍辣","辣","很辣","爆辣"};
        int []tastedGrade=new int [100];
        int []tastedNumber=new int [100];
        String str1 = new String();
        String str2 = new String();
        String str3=new String();
        String time = new String();
        String []dish=new String[]{};
        String tb = null;
        int [][]taste=new int[20][7];
        int table_count = 0;
        int i = 0, flag = 0;
        int portion = 0, number = 0;

        menu.dishes.add(menu.addDish("", 0," "));
        while (true) {
            dish=input.nextLine().split(" ");
            if(dish.length>4&&!dish[0].equals("table")||dish.length==3) {
                System.out.println("wrong format");
                continue;
            }
            if(dish.length>4&&dish[0].equals("table")){str1=dish[0];
                tb=" "+dish[1]+" "+dish[2]+" "+dish[3]+" "+dish[4]+" "+dish[5]+" "+dish[6];
                break;}
            if(dish.length==4){str1=dish[0];str2=dish[2];str3=dish[1];}
            if(dish.length==2){str1=dish[0];str2=dish[1];}
            if(dish.length==1&&dish[0].equals("end")){str1=dish[0];break;}
            if(dish.length==1&&!dish[0].equals("end")) {
                System.out.println("wrong format");
                continue;
            }
            if (dish.length==4) {
                if(dish[3].equals("T")&&isNumeric(str2)&&!isNumeric(str3)) {
                    menu.dishes.get(menu.dishes.size() - 1).isT = true;
                    menu.dishes.get(menu.dishes.size() - 1).taste = str3;
                    menu.dishes.get(menu.dishes.size() - 1).name = str1;
                    menu.dishes.get(menu.dishes.size() - 1).price = Integer.parseInt(str2);
                }
                else {
                    System.out.println("wrong format");
                    continue;
                }
            }
            else str3=" ";
            if(isNumeric(str1)||!isNumeric(str2)) {
                System.out.println("wrong format");
                continue;
            }

            for (i = 0; i < menu.dishes.size(); i++) {
                if (menu.dishes.get(i).equals(str1)) {
                    menu.dishes.get(i).price = Integer.parseInt(str2);
                    flag++;
                    break;
                }
            }
            if (flag == 0) {
                menu.dishes.add(menu.addDish(str1, Integer.parseInt(str2),str3));
            }
            flag = 0;
        }
        boolean first = false;
        if(str1.equals("end"))return ;
        while(!str1.equals("end")){
            if(str1.equals("end"))break;
            int chuanGrade=0;
            int chuanNumber=0;
            int zheGrade=0;
            int zheNumber=0;
            int jinGrade=0;
            int jinNumber=0;
            String []a=new String[]{};
            String ord;
            String call;
            String useName;
            Table tab= new Table();
            if(first)
                ord = input.nextLine();
            else {
                ord = tb;
                first=true;
            }
            a=ord.split(" ");
            str2=a[1];
            useName=a[3];
            call=a[4];
            String threeCall=call.substring(0,3);
            if(useName.length()>10||call.length()!=11||searchCall(threeCall)){
                System.out.println("wrong format");
                break;
            }
            String[] Date = a[5].split("/");
            String[] Time =a[6].split("/");
            tab.num = Integer.parseInt(str2);
            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]);
            }
            try {
                tab.time = LocalDateTime.of(intDate[0],intDate[1],intDate[2],intTime[0],intTime[1],intTime[2]);

                tables.add(tab);
                if(!tab.isOpen()) {
                    System.out.println("table " + str2 + " out of opening hours");
                    while(true){
                        str1=input.next();
                        if(str1.equals("end")||str1.equals("table"))break;
                    }
                    continue;
                }
            }catch(DateTimeException e){
                System.out.println( tab.num + " date error");
                break;
            }
            System.out.println("table "+str2+": ");
            while (true) {
                str1 = input.next();
                if (str1.equals("end"))
                    break;
                if (str1.equals("table"))
                    break;
                str2 = input.next();

                if (isNumeric(str2)) {

                    boolean exist = false;
                    for(int j=0;j<tables.size();j++) {
                        if(tables.get(j).num==Integer.parseInt(str1)) {
                            exist = true;
                            break;
                        }
                    }

                    if(exist) {
                        System.out.print(Integer.parseInt(str2) + " table " +tables.get(table_count).num + " pay for table "
                                + Integer.parseInt(str1) + " ");
                        String str=str1;
                        Record treat = new Record();
                        str1 = input.next();
                        treat.ds = menu.dishes.get(menu.searchDish(str1));
                        if(menu.searchDish(str1)!=-1){
                            if (menu.dishes.get(menu.searchDish(str1)).isT) {
                                str3 = input.next();
                                tastedGrade[Integer.parseInt(str)] = Integer.parseInt(str3);
                            } else str3 = " ";
                        }else {
                            System.out.println(str1 + " does not exist");
                            str1=input.nextLine();continue;
                        }
                        portion = input.nextInt();
                        number = input.nextInt();
                        tastedNumber[Integer.parseInt(str)]=number;
                        treat.portion = portion;
                        treat.number = number;
                        System.out.print(treat.getPrice() + "\n");
                        if(menu.dishes.get(menu.searchDish(str1)).taste.equals("晋菜")) {
                            if(Integer.parseInt(str3)<0||Integer.parseInt(str3)>4){
                                System.out.println("acidity num out of range :"+jinGrade);
                                str1=input.nextLine();
                                continue;
                            }
                            taste[Integer.parseInt(str)-1][1] += Integer.parseInt(str3)*number;
                            taste[Integer.parseInt(str)-1][4]+=number;
                        }
                        if(menu.dishes.get(menu.searchDish(str1)).taste.equals("川菜")) {
                            if(Integer.parseInt(str3)<0||Integer.parseInt(str3)>5){
                                System.out.println("spicy num out of range :"+str3);
                                str1=input.nextLine();
                                continue;
                            }
                            taste[Integer.parseInt(str)-1][0] += Integer.parseInt(str3)*number;
                            taste[Integer.parseInt(str)-1][3]+=number;
                        }
                        if(menu.dishes.get(menu.searchDish(str1)).taste.equals("浙菜")) {
                            if(Integer.parseInt(str3)<0||Integer.parseInt(str3)>3){
                                System.out.println("sweetness num out of range :"+str3);
                                str1=input.nextLine();
                                continue;
                            }
                            taste[Integer.parseInt(str)-1][2] += Integer.parseInt(str3)*number;
                            taste[Integer.parseInt(str)-1][5]+=number;
                        }

                        tables.get(table_count).add(menu, "代点",str2, str1, portion, number);
                    }

                    else {
                        System.out.println("Table number :"+Integer.parseInt(str1)+" does not exist");
                    }
                }

                else {

                    if (!str2.equals("delete")) {
                        boolean t=false;
                        if(menu.searchDish(str2)!=-1) {
                            if (menu.dishes.get(menu.searchDish(str2)).isT) {
                                hash.put(str1, menu.dishes.get(menu.searchDish(str2)).taste);
                                str3 = input.next();
                                portion = input.nextInt();
                                number = input.nextInt();
                                tastedGrade[Integer.parseInt(str1)] = Integer.parseInt(str3);
                                tastedNumber[Integer.parseInt(str1)] = number;
                                t = true;
                                if (menu.dishes.get(menu.searchDish(str2)).taste.equals("晋菜")) {
                                    if (Integer.parseInt(str3) < 0 || Integer.parseInt(str3) > 4) {
                                        System.out.println("acidity num out of range :" + str3);
                                        str1 = input.nextLine();
                                        continue;
                                    }
                                    jinGrade += Integer.parseInt(str3) * number;
                                    jinNumber += number;
                                }
                                if (menu.dishes.get(menu.searchDish(str2)).taste.equals("川菜")) {
                                    if (Integer.parseInt(str3) < 0 || Integer.parseInt(str3) > 5) {
                                        System.out.println("spicy num out of range :" + str3);
                                        str1 = input.nextLine();
                                        continue;
                                    }
                                    chuanGrade += Integer.parseInt(str3) * number;
                                    chuanNumber += number;
                                }
                                if (menu.dishes.get(menu.searchDish(str2)).taste.equals("浙菜")) {
                                    if (Integer.parseInt(str3) < 0 || Integer.parseInt(str3) > 3) {
                                        System.out.println("sweetness num out of range :" + str3);
                                        str1 = input.nextLine();
                                        continue;
                                    }
                                    zheGrade += Integer.parseInt(str3) * number;
                                    zheNumber += number;
                                }
                            } else str3 = " ";
                        }else  {
                            System.out.println(str2 + " does not exist");
                            str1=input.nextLine();continue;
                        }
                        if(t==false) {
                            portion = input.nextInt();
                            number = input.nextInt();
                        }
                    }
                    tables.get(table_count).add(menu, str3,str1, str2, portion, number);
                    if(str2.equals("delete")){
                        if(hash.get(str1).equals("晋菜")) {
                            jinGrade -= tastedGrade[Integer.parseInt(str1)];
                            jinNumber -= tastedNumber[Integer.parseInt(str1)];
                        }
                        if(hash.get(str1).equals("川菜")) {
                            chuanGrade -= tastedGrade[Integer.parseInt(str1)];
                            chuanNumber -= tastedNumber[Integer.parseInt(str1)];
                        }
                        if(hash.get(str1).equals("浙菜")) {
                            zheGrade -= tastedGrade[Integer.parseInt(str1)];
                            zheNumber -= tastedNumber[Integer.parseInt(str1)];
                        }
                        hash.put(str1,"");
                    }
                }
            }
            taste[table_count][0]=chuanGrade;
            taste[table_count][1]=jinGrade;
            taste[table_count][2]=zheGrade;
            taste[table_count][3]=chuanNumber;
            taste[table_count][4]=jinNumber;
            taste[table_count][5]=zheNumber;

            tables.get(table_count).getSum();
            int sum=0;
            String str=useName+" "+call+" "+tables.get(table_count).sum;
            String []b=new String[]{};
            if(table_count==0)customer[cnt++]=str;
            else {
                b = str.split(" ");
                boolean r=true;
                for (int l = 0; l < cnt; l++) {
                    String[] c = customer[l].split(" ");
                    if (b[0].equals(c[0])) {
                        sum = Integer.parseInt(c[2]) + Integer.parseInt(b[2]);
                        customer[l] = useName + " " + call + " " + sum;
                        r=false;
                    }
                }
                if(r)customer[cnt++]=str;
            }
            table_count++;
        }

        for (i = 0; i < table_count; i++) {
            if (tables.get(i).isOpen()) {
                System.out.print("table " + tables.get(i).num + ": " + tables.get(i).origSum+" "+tables.get(i).sum);
                for(int j=0;j<3;j++){
                    if(taste[i][j+3]!=0){
                        if(j==0){
                            System.out.print(" 川菜 "+taste[i][j+3]+" "+chuan[(int) Math.round(1.0*taste[i][j]/taste[i][j+3])]);
                        }
                        if(j==1){
                            System.out.print(" 晋菜 "+taste[i][j+3]+" "+jin[(int) Math.round(1.0*taste[i][j]/taste[i][j+3])]);
                        }
                        if(j==2){
                            System.out.print(" 浙菜 "+taste[i][j+3]+" "+zhe[(int) Math.round(1.0*taste[i][j]/taste[i][j+3])]);
                        }
                    }
                }
                System.out.println();
            } else
                System.out.println("table " + tables.get(i).num + " out of opening hours");
        }
        Arrays.sort(customer,0,cnt);
        for(int j=0;j<cnt;j++) {
            if(j<cnt-1)
                System.out.println(customer[j]);
            else System.out.print(customer[j]);
        }
    }

}
class Dish {
    String name;
    int price;
    String taste;

    boolean isT = false;
}
class Record {
    int orderNum;
    Dish ds;
    int portion;
    int number;
    boolean isDeleted = false;

    int getPrice() {
        if (portion == 2)
            return (int) Math.round(1.5 * ds.price) * number;
        else if (portion == 3)
            return 2 * ds.price * number;
        else
            return ds.price * number;
    }
}

class Table {
    Order order = new Order();
    int num;
    LocalDateTime time;
    long sum = 0;
    long origSum = 0;
    void add(Menu menu, String str3,String str1, String str2, int portion, int number) { 
        if (str2.equals("delete")) {
            order.delARecordByOrderNum(Integer.parseInt(str1));
        } else {
            if (menu.searchDish(str2) != -1) {
                order.records.add(order.addARecord(str3,Integer.parseInt(str1), str2, portion, number, menu));
            } else
                System.out.println(str2 + " does not exist");
        }
    }

    void getSum() {
        double ts = time.getHour() + time.getMinute() / 60;
        int wek = time.getDayOfWeek().getValue();
        for (int i = 0; i < order.records.size(); i++) {
            if (!order.records.get(i).isDeleted) {
                origSum += order.records.get(i).getPrice();
                if ((wek == 7 || wek == 6) && (ts >= 9.5) && (ts <= 21))
                    sum += order.records.get(i).getPrice();
                if ((wek >= 1 && wek <= 5) && (ts >= 17) && (ts <= 20.5)) {
                    if(!order.records.get(i).ds.isT)
                        sum += Math.round(order.records.get(i).getPrice() * 0.8);
                    else sum += Math.round(order.records.get(i).getPrice() * 0.7);
                }
                if ((wek >= 1 && wek <= 5) && (ts >= 10.5) && (ts <= 14.5)) {
                    if(!order.records.get(i).ds.isT)
                        sum += Math.round(order.records.get(i).getPrice() * 0.6);
                    else sum += Math.round(order.records.get(i).getPrice() * 0.7);
                }

            }
        }
    }

    boolean isOpen() {
        int weekday = time.getDayOfWeek().getValue();
        if (weekday > 0 && weekday < 6) {
            if (time.getHour() >= 17 && time.getHour() < 20)
                return true;
            if (time.getHour() == 20) {
                if (time.getMinute() <= 30)
                    return true;
            }
            if (time.getHour() > 10 && time.getHour() < 14)
                return true;
            if (time.getHour() == 10) {
                if (time.getMinute() >= 30)
                    return true;
            }
            if (time.getHour() == 14) {
                if (time.getMinute() <= 30)
                    return true;
            }
        } else {
            if (time.getHour() > 9 && time.getHour() < 21)
                return true;
            if (time.getHour() == 9) {
                if (time.getMinute() >= 30)
                    return true;
            }
            if (time.getHour() == 21) {
                if (time.getMinute() <= 30)
                    return true;
            }
        }
        return false;

    }

    public static boolean checkDateFormat(String tempDate) {

        if (tempDate.length() != 10 ){
            return false;
        }
        for (int i = 0; i < 4; i++) {
            if (tempDate.charAt(i) > 57 || tempDate.charAt(i) < 48) {
                return false;
            }
        }
        if (tempDate.charAt(5) > 57 || tempDate.charAt(5) < 48 || tempDate.charAt(6) > 57 || tempDate.charAt(6) < 48) {
            return false;
        }
        if (tempDate.charAt(8) > 57 || tempDate.charAt(8) < 48 || tempDate.charAt(9) > 57 || tempDate.charAt(9) < 48) {
            return false;
        }
        if (tempDate.charAt(7) !=45 || tempDate.charAt(4) !=45) {
            return false;
        }
        if (tempDate.charAt(5) > 49 || (tempDate.charAt(5) == 49 && tempDate.charAt(6) > 50)) {
            return false;
        }
        if (tempDate.charAt(8) > 51 || (tempDate.charAt(8) == 51 && tempDate.charAt(9) > 49)) {
            return false;
        }
        return true;
    }

    public static boolean checkSpecialDate(int[] arrayTemp) {

        if (arrayTemp[1] == 2 && arrayTemp[2] > 29) {
            return false;
        }
        if (arrayTemp[1] < 8) {
            if (arrayTemp[1] % 2 == 0 && arrayTemp[2] > 30) {return false;}
        }
        if (arrayTemp[1] > 7) {
            if (arrayTemp[1] % 2 == 1 && arrayTemp[2] > 30) {return false;}
        }
        if (arrayTemp[0] % 4 != 0 || (arrayTemp[0] % 100 == 0 && arrayTemp[0] % 400 != 0)) {
            if (arrayTemp[1] == 2 && arrayTemp[2] > 28) {return false;}
        }
        return true;
    }
}

class Menu {
    ArrayList<Dish> dishes = new ArrayList<Dish>();

    int searchDish(String dishName) {
        for (int i = 0; i < dishes.size(); i++) {
            if (dishName.equals(dishes.get(i).name)) {
                return i;
            }
        }
        return -1;
    }

    Dish addDish(String dishName, int price,String taste) {
        Dish newDish = new Dish();
        newDish.name = dishName;
        newDish.price = price;
        newDish.taste=taste;
        return newDish;
    }
}
class Order {
    ArrayList<Record> records = new ArrayList<Record>();

    Record addARecord(String tasteGrade,int orderNum, String dishName, int portion, int number, Menu menu) {
        Record newRecord = new Record();
        newRecord.orderNum = orderNum;
        newRecord.ds = menu.dishes.get(menu.searchDish(dishName));
        newRecord.portion = portion;
        newRecord.number = number;
        if(!tasteGrade.equals("代点"))
            System.out.println(newRecord.orderNum + " " + newRecord.ds.name + " " + newRecord.getPrice());
        return newRecord;
    }

    boolean delARecordByOrderNum(int orderNum) {
        int i = 0, flag = 0;
        for (i = 0; i < records.size(); i++) {
            if (records.get(i).orderNum == orderNum) {
                if (records.get(i).isDeleted == false) {
                    records.get(i).isDeleted = true;
                }
                else {
                    System.out.println("deduplication " + orderNum);
                }
                flag++;
            }
        }
        if (flag == 0) {
            System.out.println("delete error;");
            return false;
        }
        return true;
    }
}

本题基于上一次点菜计价问题进一步深入探究,对类,对象,循环,数组的知识点均有考察,是一道综合性较强的问题。做题思路:利用while循环,以end为结束标志符实现可控制范围输入,利用对象数组DishType存储数据,引入一个标志变量flag以判断语句处理数据并进行输出。对我们各种情况的剥析能力要求更高。以下为各个类的功能示意,可供参考:

菜品类:对应菜谱上一道菜的信息。
Dish {
String name;//菜品名称
int unit_price; //单价
int getPrice(int portion)//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份)
}

菜谱类:对应菜谱,包含饭店提供的所有菜的信息。
Menu {
Dish[] dishs ;//菜品数组,保存所有菜品信息
Dish searthDish(String dishName)//根据菜名在菜谱中查找菜品信息,返回Dish对象。
}

点菜记录类:保存订单上的一道菜品记录
Record {
Dish d;//菜品
int portion;//份额(1/2/3代表小/中/大份)
int getPrice()//计价,计算本条记录的价格
}

订单类:保存用户点的所有菜的信息。
Order {
Record[] records;//保存订单上每一道的记录
int getTotalPrice()//计算订单的总价
Record addARecord(String dishName,int portion)
//添加一条菜品信息到订单中。
}

以下为类图:

以下为测试结果:

 

踩坑心得及总结:

当我们学习编程时,了解问题的背景和需求很重要。我们需要明确解决方案的目标,然后使用面向对象编程的原则来设计系统并编写结构良好的代码。在Java中,我们可以使用类和对象来模拟现实世界中的概念和实体。通过将功能模块化,我们可以降低代码的复杂性并增加可维护性。使用适当的数据结构和算法,可以提高程序的性能。通过解决具体问题,并逐步挑战更复杂的任务,我们可以提高我们的编码技能。这些任务可以涵盖各个领域,如数学、经济学和游戏开发,从而让我们学以致用。此外,我们还可以通过解决一些具有挑战性的问题来提高我们的编程思维能力。这些问题可能涉及到复杂的逻辑和算法,需要创造性的解决方案。它们可以使我们适应在实际工作中遇到的各种情况。总的来说,通过合理的问题分析和代码设计,以及不断挑战自己解决更复杂问题的能力,我们可以逐渐提高我们的编程技能和思维水平。这将使我们能够更好地应对实际编程任务并提供高质量的解决方案。当我们学习编程时,了解问题的背景和需求很重要。我们需要明确解决方案的目标,然后使用面向对象编程的原则来设计系统并编写结构良好的代码。 在Java中,我们可以使用类和对象来模拟现实世界中的概念和实体。通过将功能模块化,我们可以降低代码的复杂性并增加可维护性。使用适当的数据结构和算法,可以提高程序的性能。 通过解决具体问题,并逐步挑战更复杂的任务,我们可以提高我们的编码技能。这些任务可以涵盖各个领域,如数学、经济学和游戏开发,从而让我们学以致用。 此外,我们还可以通过解决一些具有挑战性的问题来提高我们的编程思维能力。这些问题可能涉及到复杂的逻辑和算法,需要创造性的解决方案。它们可以使我们适应在实际工作中遇到的各种情况。 总的来说,通过合理的问题分析和代码设计,以及不断挑战自己解决更复杂问题的能力,我们可以逐渐提高我们的编程技能和思维水平。这将使我们能够更好地应对实际编程任务并提供高质量的解决方案。 如果您还有其他问题,我会很乐意继续帮助您!

当我们学习编程时,了解问题的背景和需求很重要。我们需要明确解决方案的目标,然后使用面向对象编程的原则来设计系统并编写结构良好的代码。 在Java中,我们可以使用类和对象来模拟现实世界中的概念和实体。通过将功能模块化,我们可以降低代码的复杂性并增加可维护性。使用适当的数据结构和算法,可以提高程序的性能。 通过解决具体问题,并逐步挑战更复杂的任务,我们可以提高我们的编码技能。这些任务可以涵盖各个领域,如数学、经济学和游戏开发,从而让我们学以致用。 此外,我们还可以通过解决一些具有挑战性的问题来提高我们的编程思维能力。这些问题可能涉及到复杂的逻辑和算法,需要创造性的解决方案。它们可以使我们适应在实际工作中遇到的各种情况。 总的来说,通过合理的问题分析和代码设计,以及不断挑战自己解决更复杂问题的能力,我们可以逐渐提高我们的编程技能和思维水平。这将使我们能够更好地应对实际编程任务并提供高质量的解决方案。 如果您还有其他问题,我会很乐意继续帮助您!