首页 > 编程语言 >Java学习3——第七至十 一次题目集以及第三阶段学习的分析与总结

Java学习3——第七至十 一次题目集以及第三阶段学习的分析与总结

时间:2023-06-27 22:33:41浏览次数:72  
标签:空格 Java String get int 学习 judge 至十 public

一.前言

     本次Blog是对java学习中第三阶段的一个总结,作为刚学习JAVA不久的小白,以下依旧只是本人作为普通学生,以当前能力和状态所做出的总结和分析,不足之处也欢迎各位大佬的指正!

  第七至第十一次题目集,总体题量都比较少,其中较多的也就5道题,其它的就1道。总体难度较第四-六次题目集有所下降。因为原来迭代后较难的题目只进行了一次另一方向的迭代就没有再迭代下去,而这次的那几道新的有迭代的题目,迭代还较少,所以比之前题目的结构更简单,错误输出状况也更少,而且其他题目则是实践一些类的功能和方法,难度比较低。

  第七次题目集是之前菜单题目的另一方向迭代,与那次相比强化了数据的格式化输出(种类增加了不少),对于数据的处理要求也更高了,需储存和处理的数据也更多了,也因此输出错误的情况也增加了不少,总体难度是偏高的。第八次题目集为新的迭代题目,主要考察了数据输入的处理、归类、存储与计算,结果的格式化输出以及类的继承和聚合关系。第九次题目集主要考察了字符串的分类处理和辨析,以及存储计数。第十次题目集中有一道第八次题目集题目的迭代,主要增加了数据分类的类数和数据处理的复杂性,其它题目主要考察了Hashmap对数据的检索、排序和抽象类的多态问题。第十一次题目集里有一道在第十次题目集中迭代题的基础上进一步迭代的题目,主要考察了多类之间的组合关系,并进一步增加了数据处理、存储、格式化输出的复杂性,也增加了错误情况的输出种类。

二.代码的设计分析与踩坑心得以及改进意见

 因为题目较多,以下只选取关键题目进行分析总结

 1.第七次题目集

  7-1 菜单计价程序-5

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

 

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

 

参考以下类的模板进行设计:菜品类:对应菜谱上一道菜的信息。

 

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)//根据序号查找一条记录

 

}

 

###输入格式:

 

桌号标识格式:table + 序号 +英文空格+ 日期(格式:YYYY/MM/DD)+英文空格+ 时间(24小时制格式: HH/MM/SS)

 

菜品记录格式:

 

菜名+英文空格+基础价格

 

如果有多条相同的菜名的记录,菜品的基础价格以最后一条记录为准。

 

点菜记录格式:序号+英文空格+菜名+英文空格+份额+英文空格+份数注:份额可输入(1/2/3), 1代表小份,2代表中份,3代表大份。

 

删除记录格式:序号 +英文空格+delete

 

代点菜信息包含:桌号+英文空格+序号+英文空格+菜品名称+英文空格+份额+英文空格+分数

 

最后一条记录以“end”结束。

 

### 输出格式:

 

按输入顺序输出每一桌的订单记录处理信息,包括:

 

1、桌号,格式:table+英文空格+桌号+”:”

 

2、按顺序输出当前这一桌每条订单记录的处理信息,

 

每条点菜记录输出:序号+英文空格+菜名+英文空格+价格。其中的价格等于对应记录的菜品\*份数,序号是之前输入的订单记录的序号。如果订单中包含不能识别的菜名,则输出“\*\* does not exist”,\*\*是不能识别的菜名

 

如果删除记录的序号不存在,则输出“delete error”

 

最后按输入顺序一次输出每一桌所有菜品的总价(整数数值)格式:table+英文空格+桌号+“:”+英文空格+当前桌的总价

 

以上为菜单计价系列-3的题目要求,加粗的部分是有调整的内容。本次课题相比菜单计价系列-3新增要求如下:

 

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金额都要累加。

 

输出用户支付金额格式:

 

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

 

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

 

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

 

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

 

输入格式:

 

桌号标识格式:table + 序号 +英文空格+ 日期(格式:YYYY/MM/DD)+英文空格+ 时间(24小时制格式: HH/MM/SS)

 

菜品记录格式:

 

菜名+口味类型+英文空格+基础价格

 

如果有多条相同的菜名的记录,菜品的基础价格以最后一条记录为准。 

 

点菜记录格式:序号+英文空格+菜名+英文空格+辣/酸/甜度值+英文空格+份额+英文空格+份数 注:份额可输入(1/2/3), 1代表小份,2代表中份,3代表大份。辣/酸/甜度取值范围见题目中说明。 

 

删除记录格式:序号 +英文空格+delete

 

代点菜信息包含:桌号+英文空格+序号+英文空格+菜品名称**+英文空格+辣/酸/甜度值+**英文空格+份额+英文空格+分数

 

最后一条记录以“end”结束。

 

输出格式:

 

按输入顺序输出每一桌的订单记录处理信息,包括:

 

1、桌号,格式:table+英文空格+桌号+“:”+英文空格 

 

2、按顺序输出当前这一桌每条订单记录的处理信息, 

 

每条点菜记录输出:序号+英文空格+菜名+英文空格+价格。其中的价格等于对应记录的菜品\*份数,序号是之前输入的订单记录的序号。如果订单中包含不能识别的菜名,则输出“\*\* does not exist”,\*\*是不能识别的菜名

 

如果删除记录的序号不存在,则输出“delete error”

 

之后按输入顺序一次输出每一桌所有菜品的价格(整数数值),

 

格式:table+英文空格+桌号+“:”+英文空格+当前桌的计算折扣后总价+英文空格+辣度平均值+英文空格+酸度平均值+英文空格+甜度平均值+英文空格

 

最后按拼音顺序输出每位客户(不考虑客户同名或拼音相同的情况)的支付金额,格式: 用户姓名+英文空格+手机号+英文空格+支付总金额,按输入顺序排列。

源代码:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
public class Main {
    public static void main(String[] args){
        SolveInformation.solve();
    }
}
class SolveInformation {
    public static void solve() {
        Scanner in = new Scanner(System.in);
        String End = "end";//设立结束时会输入的字符串
        String Table = "table";//设立桌子的字符串
        String deposit = in.nextLine();
        TableInformation table = new TableInformation();
        ArrayList<OrderOtherDishes> otherDishes = new ArrayList<>();
        Menu menu = new Menu();
        Order order = new Order();
        CustomerDeposit customers = new CustomerDeposit();
        SpecialRecord sRecords = new SpecialRecord();
        ArrayList<TableNumAndPrice> numAndPrice = new ArrayList<>();
        ArrayList<Delete> delete = new ArrayList<>();//用于记录每桌每次delete的序号
        while (deposit.indexOf(Table) == -1 && deposit.indexOf(End) == -1) {
            ifMenuError(deposit,menu);
             deposit = in.nextLine();
        }
        while(deposit.indexOf("end") == -1) {//在输入end之前一直处理输入信息
                    if(ifTableError(deposit, table, customers) == -1) {//判断桌号是否错误
                 System.out.println("table "+table.getOrderNum()+": ");
                        deposit = in.nextLine();
                while (deposit.indexOf(Table) == -1 && deposit.indexOf(End) == -1) {
                    if (deposit.indexOf("delete") == -1) {
                        ifRecordError(deposit, order, sRecords, menu, otherDishes,table,numAndPrice);
                        deposit = in.nextLine();
                    } else {
                        String[] deletedeposit = deposit.split("[ ]");
                        Delete delete2 = new Delete();
                        delete2.setDeleteNum(Integer.parseInt(deletedeposit[0]));
                        delete2.setTableNum(table.getOrderNum());
                        int j = -1;
                        for (int i = 0; i < order.getRecordsLength(); i++) {
                                if (delete2.getDeleteNum() == order.getRecords().get(i).getOrderNum()&&delete2.getTableNum() == table.getOrderNum()){
                                    j = i;
                                    break;
                                }
                        }
                        if (j == -1) {
                            System.out.println("delete error;");
                        } else {
                            order.getRecords().remove(j);
                            for (int i = 0; i < sRecords.getChuan().size(); i++) {//检查是否为川菜
                                if (sRecords.getChuan().get(i).getOrderNum() == delete2.getDeleteNum()&&delete2.getTableNum() == sRecords.getChuan().get(i).getTableNum()) {
                                    sRecords.getChuan().remove(i);
                                }
                            }
                            for (int i = 0; i < sRecords.getJin().size(); i++) {//检查是否为晋菜
                                if (sRecords.getJin().get(i).getOrderNum() == delete2.getDeleteNum()&&delete2.getTableNum() == sRecords.getJin().get(i).getTableNum()) {
                                    sRecords.getJin().remove(i);
                                }
                            }
                            for (int i = 0; i < sRecords.getZhe().size(); i++) {//检查是否为浙菜
                                if (sRecords.getZhe().get(i).getOrderNum() == delete2.getDeleteNum()&&delete2.getTableNum() == sRecords.getZhe().get(i).getTableNum()) {
                                    sRecords.getZhe().remove(i);
                                }
                            }
                            int k = -1;
                            for (Delete d : delete) {
                                if (d.getDeleteNum() == Integer.parseInt(deletedeposit[0])) {
                                    k = 0;
                                }
                            }
                            if (k == -1){
                                Delete delete1 = new Delete();
                                delete1.setDeleteNum(Integer.parseInt(deletedeposit[0]));
                                delete1.setTableNum(table.getOrderNum());
                                delete.add(delete1);
                            }

                            else
                                System.out.println("deduplication " + Integer.parseInt(deletedeposit[0]));
                        }
                        deposit = in.nextLine();
                    }
                }

               numAndPrice.add(addEndInformation(table.getOrderNum(), (double) Math.round(order.getTotalPrice(table, menu)), order.getInitialTotalPrice(menu)));
                int point = customers.searchCustomer(table.getCustomer().getName());
                customers.getCustomers().get(point).setPay(customers.getCustomers().get(point).getPay() + (double) Math.round(order.getTotalPrice(table, menu)));
                delete.clear();//清除存储的删除记录
                order.getRecords().clear();
            } else {
                       do{
                           deposit = in.nextLine();
                       }while(deposit.indexOf(Table) == -1&&deposit.indexOf(End) == -1);
            }
        }
if(deposit.indexOf(End) != -1){ endPrint(sRecords,customers,numAndPrice,otherDishes); } } public static boolean ifMenuError (String deposit,Menu menu) {//判断菜单信息并运行相关程序 boolean judge = false; String[] menudeposit = deposit.split("[ ]"); Pattern pattern1 = Pattern.compile("[1-9]?[0-9]([0-9]){0,2}");//金额 Pattern pattern2 = Pattern.compile("T|F");//特色菜标识格式 if (menudeposit.length == 4) {//特色菜判断格式 Matcher matcher1 = pattern1.matcher(menudeposit[2]); if (matcher1.matches() == false) { judge = true; } Matcher matcher2 = pattern2.matcher(menudeposit[3]); if (matcher2.matches() == false) { judge = true; } } if (menudeposit.length == 2) {//普通菜判断格式 Matcher matcher = pattern1.matcher(menudeposit[1]); if (matcher.matches() == false) { judge = true; } } if (deposit.indexOf("T") == -1) { //判断输入长度格式 if (menudeposit.length != 2) { judge = true; } } else { if (menudeposit.length != 4) { judge = true; } } if (judge == true) { System.out.println("wrong format"); }else { if (menu.ifRepeat(menudeposit[0]) == -1) {//判断是否重复输入 if (menudeposit.length == 4) { menu.addSpecilaDishs(menudeposit[0], Integer.parseInt(menudeposit[2]), menudeposit[3], menudeposit[1]); } if (menudeposit.length == 2) { menu.addNormalDishs(menudeposit[0], Integer.parseInt(menudeposit[1])); } }else{ menu.removeDishs(menu.ifRepeat(menudeposit[0])); if(menudeposit.length == 4) menu.addSpecilaDishs(menudeposit[0], Integer.parseInt(menudeposit[2]), menudeposit[3], menudeposit[1]); if (menudeposit.length == 2) menu.addNormalDishs(menudeposit[0], Integer.parseInt(menudeposit[1])); } } return judge; } public static int ifTableError (String deposit,TableInformation table, CustomerDeposit customers){ int judge = -1; int[] maxday = {0,31,28,31,30,31,30,31,31,30,31,30,31}; String[] tabledeposit = deposit.split("[ ]"); String[] datedeposit = tabledeposit[5].split("[/]"); String[] timedeposit = tabledeposit[6].split("[/]"); //初步格式判断 Pattern pattern = Pattern.compile("table\\s[1-9]([0-9]{1,5})?\\s:\\s[a-z]{1,10}\\s(180|181|189|133|135|136)[0-9]{8}\\s[1-9]([0-9]){3}/(10|11|12|[1-9])/[0-9]{1,2}\\s[0-9]{2}/[0-5]?[0-9]/[0-5]?[0-9]"); Matcher matcher = pattern.matcher(deposit); if(matcher.matches() == false){ judge = 0; } if(tabledeposit.length == 7&&matcher.matches() == true){ if(Integer.parseInt(datedeposit[2])>maxday[Integer.parseInt(datedeposit[1])]){ judge = 0; } if(Integer.parseInt(timedeposit[0])>23){ judge = 0; } }else{ judge = 0; } if(judge == -1){ table.setDate(tabledeposit[5]); table.setTime(tabledeposit[6]); table.setOrderNum(Integer.parseInt(tabledeposit[1])); if(table.ifopen() == false){ judge = 1; } } if(judge == 0){ System.out.println("wrong format"); } if(judge == 1){ System.out.println("table "+tabledeposit[1]+" out of opening hours"); } if(judge == -1){ table.setDate(tabledeposit[5]); table.setTime(tabledeposit[6]); table.setOrderNum(Integer.parseInt(tabledeposit[1])); table.setCustomer(tabledeposit[3],tabledeposit[4]); if(customers.searchCustomer(tabledeposit[3]) == -1) customers.addCustomers(tabledeposit[3],tabledeposit[4]); } return judge; } public static int ifRecordError(String deposit,Order order,SpecialRecord sRecords,Menu menu,ArrayList<OrderOtherDishes> otherDishes,TableInformation table,ArrayList<TableNumAndPrice> numAndPrice){ String[] recorddeposit = deposit.split("[ ]"); OrderOtherDishes others = new OrderOtherDishes(); int judge = -1;//普通 if(recorddeposit.length == 4||recorddeposit.length == 5||recorddeposit.length == 6){ if(recorddeposit.length == 4){ Pattern pattern = Pattern.compile("\\d"); Matcher matcher1 = pattern.matcher(recorddeposit[0]); Matcher matcher2 = pattern.matcher(recorddeposit[2]); Matcher matcher3 = pattern.matcher(recorddeposit[3]); if(matcher1.matches() == true&&matcher2.matches() == true&&matcher3.matches() == true){ if(menu.searthDish(recorddeposit[1]) == null){ System.out.println(recorddeposit[1]+" does not exist"); judge = 1; } }else{ System.out.println("wrong format"); } } if(recorddeposit.length == 5){ Pattern pattern = Pattern.compile("\\d"); Matcher matcher = pattern.matcher(recorddeposit[1]); Matcher matcher1 = pattern.matcher(recorddeposit[0]); Matcher matcher2 = pattern.matcher(recorddeposit[2]); Matcher matcher3 = pattern.matcher(recorddeposit[3]); Matcher matcher4 = pattern.matcher(recorddeposit[4]); if(matcher.matches() == true){ if(matcher1.matches() == true&&matcher.matches() == true&&matcher3.matches() == true&&matcher4.matches() == true){ boolean ifExist = false; for(int i = 0;i<numAndPrice.size();i++){ if(numAndPrice.get(i).getOrdernum() == Integer.parseInt(recorddeposit[0])){ ifExist = true; } } if(ifExist == true){ if(menu.searthDish(recorddeposit[2]) == null){ System.out.println(recorddeposit[2]+" does not exist"); judge = 2; }else judge = -2; //代点普通菜 }else{ System.out.println("wrong format"); judge = 2; } }else{ System.out.println("wrong format"); judge = 2; } }else{ if(matcher1.matches() == true&&matcher2.matches() == true&&matcher3.matches() == true&&matcher4.matches() == true){ if(menu.searthDish(recorddeposit[1]) == null){ System.out.println(recorddeposit[1]+" does not exist"); judge = 3; }else judge = -3;//特色菜 }else{ System.out.println("wrong format"); judge = 3; } } } if(recorddeposit.length == 6){ Pattern pattern = Pattern.compile("\\d"); Matcher matcher = pattern.matcher(recorddeposit[1]); Matcher matcher1 = pattern.matcher(recorddeposit[0]); Matcher matcher2 = pattern.matcher(recorddeposit[2]); Matcher matcher3 = pattern.matcher(recorddeposit[3]); Matcher matcher4 = pattern.matcher(recorddeposit[4]); Matcher matcher5 = pattern.matcher(recorddeposit[5]); if(matcher1.matches() == true&&matcher.matches() == true&&matcher3.matches() == true&&matcher4.matches() == true&&matcher5.matches() == true){ boolean ifExist = false; for(int i = 0;i<numAndPrice.size();i++){ if(numAndPrice.get(i).getOrdernum() == Integer.parseInt(recorddeposit[0])){ ifExist = true; } } if(ifExist == true){ if(menu.searthDish(recorddeposit[2]) == null){ System.out.println(recorddeposit[2]+" does not exist"); judge = 4; }else{ judge = -4;//代点特色菜 } }else{ System.out.println("wrong format"); judge = 4; } }else{ System.out.println("wrong format"); judge = 4; } } }else{ judge = 0; System.out.println("wrong format"); } if(judge == -1){ order.addRecord(Integer.parseInt(recorddeposit[0]),recorddeposit[1],Integer.parseInt(recorddeposit[2]),Integer.parseInt(recorddeposit[3]),menu ); judge = -5; } if(judge == -2){ order.addRecord(Integer.parseInt(recorddeposit[1]),recorddeposit[2],Integer.parseInt(recorddeposit[3]),Integer.parseInt(recorddeposit[4]),menu ); others.setTableNumber(Integer.parseInt(recorddeposit[0])); others.setDishname(recorddeposit[2]); others.setNum(Integer.parseInt(recorddeposit[4])); otherDishes.add(others); System.out.print(order.getRecords().get(order.getRecordsLength() - 1).getOrderNum() + " "); System.out.print("table "+table.getOrderNum()+" pay for table "+recorddeposit[0]); System.out.printf(" %.0f\n", order.getRecords().get(order.getRecordsLength() - 1).getInitialPrice(menu)); } if(judge == -3){ if(order.addSpecialOrder(sRecords,recorddeposit[1],Integer.parseInt(recorddeposit[2]),Integer.parseInt(recorddeposit[4]),menu,Integer.parseInt(recorddeposit[0]),table) == false){ order.addRecord(Integer.parseInt(recorddeposit[0]),recorddeposit[1],Integer.parseInt(recorddeposit[3]),Integer.parseInt(recorddeposit[4]),menu ); judge = -5; } } if(judge == -4){ boolean ifOutRange = false; if(menu.searthDish(recorddeposit[2]).getType().equals("川菜") == true){ if(Integer.parseInt(recorddeposit[3])<0||Integer.parseInt(recorddeposit[3])>5){ ifOutRange = true; System.out.println("spicy num out of range :"+Integer.parseInt(recorddeposit[3])); } } if(menu.searthDish(recorddeposit[2]).getType().equals("晋菜") == true){ if(Integer.parseInt(recorddeposit[3])<0||Integer.parseInt(recorddeposit[3])>4){ ifOutRange = true; System.out.println("acidity num out of range :"+Integer.parseInt(recorddeposit[3])); } } if(menu.searthDish(recorddeposit[2]).getType().equals("浙菜") == true){ if(Integer.parseInt(recorddeposit[3])<0||Integer.parseInt(recorddeposit[3])>3){ ifOutRange = true; System.out.println("sweetness num out of range :"+Integer.parseInt(recorddeposit[3])); } } if(ifOutRange == false){ others.setTableNumber(Integer.parseInt(recorddeposit[0])); others.setDishname(recorddeposit[2]); others.setDegree(Integer.parseInt(recorddeposit[3])); others.setType(menu.searthDish(recorddeposit[2]).getType()); others.setNum(Integer.parseInt(recorddeposit[5])); if(order.addSpecialOrder(sRecords,recorddeposit[2],Integer.parseInt(recorddeposit[5]),Integer.parseInt(recorddeposit[3]),menu,Integer.parseInt(recorddeposit[1]),table) == false) { order.addRecord(Integer.parseInt(recorddeposit[1]),recorddeposit[2],Integer.parseInt(recorddeposit[4]),Integer.parseInt(recorddeposit[5]),menu ); otherDishes.add(others); System.out.print(order.getRecords().get(order.getRecordsLength() - 1).getOrderNum() + " "); System.out.print("table "+table.getOrderNum()+" pay for table "+recorddeposit[0]); System.out.printf(" %.0f\n", order.getRecords().get(order.getRecordsLength() - 1).getInitialPrice(menu)); } } } if(judge == -5){ System.out.print(order.getRecords().get(order.getRecordsLength() - 1).getOrderNum() + " "); System.out.print(order.getRecords().get(order.getRecordsLength() - 1).getDish().getName() + " "); System.out.printf("%.0f\n", order.getRecords().get(order.getRecordsLength() - 1).getInitialPrice(menu)); } return judge; } public static TableNumAndPrice addEndInformation(int Ordernum, double TotalPrice, double InitialTotalPrice){//判断是否重复删除 TableNumAndPrice depositnumandprice = new TableNumAndPrice(); depositnumandprice.setTotalPrice(TotalPrice); depositnumandprice.setOrdernum(Ordernum); depositnumandprice.setInitialTotalPrice(InitialTotalPrice); return depositnumandprice; } public static void endPrint(SpecialRecord sRecord, CustomerDeposit customers, ArrayList<TableNumAndPrice> numAndPrice, ArrayList<OrderOtherDishes> otherDishes) { int min = 0; for (int i = 0; i < numAndPrice.size(); i++) { if (sRecord.averageSpicyDegree(otherDishes, numAndPrice.get(i).getOrdernum()) != null || sRecord.averageSourDegree(otherDishes, numAndPrice.get(i).getOrdernum()) != null || sRecord.averageSweetDegree(otherDishes, numAndPrice.get(i).getOrdernum()) != null){ System.out.printf("table %d: %.0f %.0f", numAndPrice.get(i).getOrdernum(), numAndPrice.get(i).getInitialTotalPrice(), numAndPrice.get(i).getTotalPrice()); if (sRecord.averageSpicyDegree(otherDishes, numAndPrice.get(i).getOrdernum()) != null) { int sum = 0; for (int j = 0; j < sRecord.getChuan().size(); j++) { if (sRecord.getChuan().get(j).getTableNum() == numAndPrice.get(i).getOrdernum()) sum += sRecord.getChuan().get(j).getNum(); } for (int k = 0; k < otherDishes.size(); k++) { if (numAndPrice.get(i).getOrdernum() == otherDishes.get(k).getTableNumber() && otherDishes.get(k).getType().equals("川菜")) sum += otherDishes.get(k).getNum(); } System.out.printf(" 川菜 %d %s", sum, sRecord.averageSpicyDegree(otherDishes, numAndPrice.get(i).getOrdernum())); } if (sRecord.averageSourDegree(otherDishes, numAndPrice.get(i).getOrdernum()) != null) { int sum = 0; for (int j = 0; j < sRecord.getJin().size(); j++) { if (sRecord.getJin().get(j).getTableNum() == numAndPrice.get(i).getOrdernum()) sum += sRecord.getJin().get(j).getNum(); } for (int k = 0; k < otherDishes.size(); k++) { if (numAndPrice.get(i).getOrdernum() == otherDishes.get(k).getTableNumber() && otherDishes.get(k).getType().equals("晋菜")) sum += otherDishes.get(k).getNum(); } System.out.printf(" 晋菜 %d %s", sum, sRecord.averageSourDegree(otherDishes, numAndPrice.get(i).getOrdernum())); } if (sRecord.averageSweetDegree(otherDishes, numAndPrice.get(i).getOrdernum()) != null) { int sum = 0; for (int j = 0; j < sRecord.getZhe().size(); j++) { if (sRecord.getZhe().get(j).getTableNum() == numAndPrice.get(i).getOrdernum()) sum += sRecord.getZhe().get(j).getNum(); } for (int k = 0; k < otherDishes.size(); k++) { if (numAndPrice.get(i).getOrdernum() == otherDishes.get(k).getTableNumber() && otherDishes.get(k).getType().equals("浙菜")) sum += otherDishes.get(k).getNum(); } System.out.printf(" 浙菜 %d %s", sum, sRecord.averageSweetDegree(otherDishes, numAndPrice.get(i).getOrdernum())); } }else{ System.out.printf("table %d: %.0f %.0f ", numAndPrice.get(i).getOrdernum(), numAndPrice.get(i).getInitialTotalPrice(), numAndPrice.get(i).getTotalPrice()); } System.out.printf("\n"); } while (customers.getCustomers().size() > 0) { for (int i = 0; i < customers.getCustomers().size(); i++) { if (customers.getCustomers().get(i).getName().compareTo(customers.getCustomers().get(min).getName()) < 0) { min = i; } } System.out.printf("%s %s %.0f\n",customers.getCustomers().get(min).getName(),customers.getCustomers().get(min).getNumber(),customers.getCustomers().get(min).getPay()); customers.getCustomers().remove(min);min=0; } } } class Customer { private String name; private String number; private double pay = 0.0; public Customer() { } public Customer(String name, String number, int pay) { this.name = name; this.number = number; this.pay = pay; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public double getPay() { return pay; } public void setPay(double pay) { this.pay = pay; } } class CustomerDeposit { private ArrayList<Customer> customers = new ArrayList<>(); public CustomerDeposit() { } public CustomerDeposit(ArrayList<Customer> customers) { this.customers = customers; } public ArrayList<Customer> getCustomers() { return customers; } public void addCustomers(String name,String number) { Customer customer = new Customer(); if(searchCustomer(name) == -1){ customer.setName(name); customer.setNumber(number); customers.add(customer); } } public int searchCustomer(String name){ int judge = -1; for(int i = 0;i<customers.size();i++){ if(customers.get(i).getName().equals(name) == true){ judge = i; } } return judge; } public void removeCustomers(Customer customer) { customers.remove(customer); } } class Dish { private String name; private int unit_price; private String type = "without";//看是不是特殊菜系 private boolean ifSpecial = false;//判断是否为特色菜 public Dish() { } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getUnit_price() { return unit_price; } public void setUnit_price(int unit_price) { this.unit_price = unit_price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean getIfSpecial() { return ifSpecial; } public void setIfSpecial(String a) { if(a.equals("T")){ this.ifSpecial = true; } } public int getprice(int portion) {//根据输入的份额计算每道菜的价格 double price = unit_price; int result = 0; if(portion == 2){ price*=1.5; } if(portion == 3){ price*=2.0; } result = (int)Math.round(price); return result; } } class Menu { private ArrayList<Dish> dishs = new ArrayList<>();//存储菜谱信息 public ArrayList<Dish> getDishs() { return dishs; } public Menu() { } public void addNormalDishs(String dishName, int unit_price) { Dish dish = new Dish(); dish.setName(dishName); dish.setUnit_price(unit_price); dishs.add(dish); } public void addSpecilaDishs(String dishName, int unit_price, String ifSprcial, String dishType) { Dish dish = new Dish(); dish.setName(dishName); dish.setUnit_price(unit_price); dish.setIfSpecial(ifSprcial); dish.setType(dishType); dishs.add(dish); } public Dish searthDish(String dishName){ int deposit = -1; for(int i = 0;i<dishs.size();i++){ if(dishs.get(i).getName().equals(dishName)){ deposit = i; break; } } if(deposit != -1) return dishs.get(deposit); else return null; } public int ifRepeat(String name){//如果为重复添加,返回已存的菜在menu里的下标 int subscript = -1; for(int i = 0;i<dishs.size();i++){ if(dishs.get(i).getName().equals(name) == true){ subscript = i;break; } } return subscript; } public void removeDishs(int i) { dishs.remove(i); } } class Order { private ArrayList<Record> records = new ArrayList<>();//存储普通点菜记录信息 public Order() { } public double getTotalPrice(TableInformation table, Menu menu) {//获得折扣后总价 double sum = 0; for(int i = 0;i<records.size();i++) { sum += records.get(i).getDiscountPrice(table,menu); } return sum; } public int getInitialTotalPrice(Menu menu){//获得折扣前总价 int sum = 0; for(int i = 0;i<records.size();i++) { sum += records.get(i).getInitialPrice(menu); } return sum; } public void addRecord(int orderNum, String dishName, int portion, int num, Menu menu){ Record record = new Record(); record.setOrderNum(orderNum); record.setDish(menu.searthDish(dishName)); record.setNum(num); record.setPortion(portion); records.add(record); } public boolean addSpecialOrder( SpecialRecord record, String dishName, int degree, int num,Menu menu,int orderNum,TableInformation table){ boolean judge = true; if(menu.searthDish(dishName).getType().equals("川菜") == true){ if(degree>=0&&degree<=5){ record.addSichuanCuisine(dishName,num,degree,orderNum,table); judge = false; }else{ System.out.println("spicy num out of range :"+degree); } } if(menu.searthDish(dishName).getType().equals("晋菜") == true){ if(degree>=0&&degree<=4){ record.addJinCuisine(dishName,num,degree,orderNum,table); judge = false; }else{ System.out.println("acidity num out of range :"+degree); } } if(menu.searthDish(dishName).getType().equals("浙菜") == true){ if(degree>=0&&degree<=3){ record.addZhejiangCuisine(dishName,num,degree,orderNum,table); judge = false; }else{ System.out.println("sweetness num out of range :"+degree); } } return judge; } public ArrayList<Record> getRecords(){ return this.records; } public int getRecordsLength(){ return this.records.size(); } public void delARecordByOrderNum(int orderNum){//删除对应记录 records.remove(findRecordByNum(orderNum)); } public int findRecordByNum(int orderNum){//找寻对应记录 int judge = -1; for(int i = 0;i<records.size();i++) { if(records.get(i).getOrderNum() == orderNum){ judge = i;break; } } return judge; } } class OrderOtherDishes { private int tableNumber; private int degree = 0; private String dishname; private String type = "without"; private int num = 0; public OrderOtherDishes() { } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getTableNumber() { return tableNumber; } public void setTableNumber(int tableNumber) { this.tableNumber = tableNumber; } public int getDegree() { return degree; } public void setDegree(int degree) { this.degree = degree; } public String getDishname() { return dishname; } public void setDishname(String dishname) { this.dishname = dishname; } public String getType() { return type; } public void setType(String type) { this.type = type; } } class Record { private int orderNum; private Dish d; private int portion; private int num;//份数 public Record() { } public double getDiscountPrice(TableInformation table,Menu menu){//得到每条记录的菜的折扣后价格 double price; if(d.getIfSpecial() == true&&table.ifWeekend() == false) price = Math.round(getInitialPrice(menu)*0.7 ); else price = Math.round(getInitialPrice(menu)*table.discount()); return price; } public double getInitialPrice(Menu menu){//得到每条记录的菜的折扣前价格 double price; price = Math.round(menu.searthDish(d.getName()).getprice(portion)*num); return price; } public int getOrderNum() { return orderNum; } public void setOrderNum(int orderNum) { this.orderNum = orderNum; } public Dish getDish() { return d; } public void setDish(Dish d) { this.d = d; } public int getPortion() { return portion; } public void setPortion(int portion) { this.portion = portion; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } } class SichuanCuisine {//川菜类 private String name; private int spicydegree = 0; private int num = 0; private int orderNum; private int tableNum; public SichuanCuisine() { } public int getTableNum() { return tableNum; } public void setTableNum(int tableNum) { this.tableNum = tableNum; } public SichuanCuisine(String name, int num, int spicydegree, int orderNum,int tableNum) { this.name = name; this.spicydegree = spicydegree; this.num = num; this.orderNum = orderNum; this.tableNum = tableNum; } public int getOrderNum() { return orderNum; } public void setOrderNum(int orderNum) { this.orderNum = orderNum; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSpicydegree() { return spicydegree; } public void setSpicydegree(int spicydegree) { this.spicydegree = spicydegree; } } class JinCuisine {//晋菜类 private String name; private int sourdegree = 0; private int num = 0; private int orderNum; private int tableNum; public JinCuisine() { } public int getTableNum() { return tableNum; } public void setTableNum(int tableNum) { this.tableNum = tableNum; } public JinCuisine(String name, int num, int sourdegree, int orderNum,int tableNum) { this.name = name; this.orderNum = orderNum; this.sourdegree = sourdegree; this.num = num; this.tableNum = tableNum; } public int getOrderNum() { return orderNum; } public void setOrderNum(int orderNum) { this.orderNum = orderNum; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSourdegree() { return sourdegree; } public void setSourdegree(int sourdegree) { this.sourdegree = sourdegree; } } class ZhejiangCuisine {//浙菜类 private String name; private int sweetdegree = 0; private int num = 0; private int orderNum; private int tableNum; public ZhejiangCuisine() { } public int getTableNum() { return tableNum; } public void setTableNum(int tableNum) { this.tableNum = tableNum; } public ZhejiangCuisine(String name, int num, int sweetdegree, int orderNum, int tableNum) { this.name = name; this.sweetdegree = sweetdegree; this.num = num; this.orderNum = orderNum; this.tableNum = tableNum; } public int getOrderNum() { return orderNum; } public void setOrderNum(int orderNum) { this.orderNum = orderNum; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSweetdegree() { return sweetdegree; } public void setSweetdegree(int sweetdegree) { this.sweetdegree = sweetdegree; } } class SpecialRecord {//特色菜类 private ArrayList<JinCuisine> jin = new ArrayList<>(); private ArrayList<SichuanCuisine> chuan = new ArrayList<>(); private ArrayList<ZhejiangCuisine> zhe = new ArrayList<>(); public SpecialRecord() { } public ArrayList<JinCuisine> getJin() { return jin; } public ArrayList<SichuanCuisine> getChuan() { return chuan; } public ArrayList<ZhejiangCuisine> getZhe() { return zhe; } public void setJin(ArrayList<JinCuisine> jin) { this.jin = jin; } public void setChuan(ArrayList<SichuanCuisine> chuan) { this.chuan = chuan; } public void setZhe(ArrayList<ZhejiangCuisine> zhe) { this.zhe = zhe; } public String averageSpicyDegree(ArrayList<OrderOtherDishes> otherDishes,int tableNum){//计算平均辣度 int average; int sumdegree = 0,sum = 0; String averageDegree = new String(); for(int i = 0;i<chuan.size();i++){ if(chuan.get(i).getTableNum() == tableNum){ sumdegree += chuan.get(i).getSpicydegree()*chuan.get(i).getNum(); sum += chuan.get(i).getNum(); } } for(int i = 0;i<otherDishes.size();i++){ if(otherDishes.get(i).getTableNumber() == tableNum&&otherDishes.get(i).getType().equals("川菜")){ if(otherDishes.get(i).getDegree()>0) sum+=(otherDishes.get(i).getDegree()*otherDishes.get(i).getNum()); if(otherDishes.get(i).getDegree() == 0) sum += otherDishes.get(i).getNum(); } } if(sum != 0){ average = (int)Math.round(sumdegree*1.0/sum); switch(average){ case 0: averageDegree = "不辣";break; case 1: averageDegree = "微辣";break; case 2: averageDegree = "稍辣";break; case 3: averageDegree = "辣";break; case 4: averageDegree = "很辣";break; case 5: averageDegree = "爆辣";break; } }else averageDegree = null; return averageDegree; } public String averageSourDegree(ArrayList<OrderOtherDishes> otherDishes,int tableNum){//计算平均酸度 int average; int sumdegree = 0,sum = 0; String averageDegree = new String(); for(int i = 0;i<jin.size();i++){ if(jin.get(i).getTableNum() == tableNum){ sumdegree += jin.get(i).getSourdegree()*jin.get(i).getNum(); sum += jin.get(i).getNum(); } } for(int i = 0;i<otherDishes.size();i++){ if(otherDishes.get(i).getTableNumber() == tableNum&&otherDishes.get(i).getType().equals("晋菜")){ if(otherDishes.get(i).getDegree()>0) sum+=(otherDishes.get(i).getDegree()*otherDishes.get(i).getNum()); if(otherDishes.get(i).getDegree() == 0) sum += otherDishes.get(i).getNum(); } } if(sum!= 0){ average = (int)Math.round(sumdegree*1.0/sum); switch(average){ case 0: averageDegree = "不酸";break; case 1: averageDegree = "微酸";break; case 2: averageDegree = "稍酸";break; case 3: averageDegree = "酸";break; case 4: averageDegree = "很酸";break; } }else averageDegree = null; return averageDegree; } public String averageSweetDegree(ArrayList<OrderOtherDishes> otherDishes,int tableNum){//计算平均甜度 int average; int sumdegree = 0,sum = 0; String averageDegree = new String(); for(int i = 0;i<zhe.size();i++){ if(zhe.get(i).getTableNum() == tableNum){ sumdegree += zhe.get(i).getSweetdegree()*zhe.get(i).getNum(); sum += zhe.get(i).getNum(); } } for(int i = 0;i<otherDishes.size();i++){ if(otherDishes.get(i).getTableNumber() == tableNum&&otherDishes.get(i).getType().equals("浙菜")){ if(otherDishes.get(i).getDegree()>0) sum += (otherDishes.get(i).getDegree()*otherDishes.get(i).getNum()); if(otherDishes.get(i).getDegree() == 0) sum += otherDishes.get(i).getNum(); } } if(sum != 0){ average = (int)Math.round(sumdegree*1.0/sum); switch(average){ case 0: averageDegree = "不甜";break; case 1: averageDegree = "微甜";break; case 2: averageDegree = "稍甜";break; case 3: averageDegree = "甜";break; } }else averageDegree = null; return averageDegree; } public void addJinCuisine(String dishName, int num, int degree,int orderNum,TableInformation table) { JinCuisine jin = new JinCuisine(dishName,num,degree,orderNum,table.getOrderNum()); this.jin.add(jin); } public void addSichuanCuisine(String dishName, int num, int degree,int orderNum,TableInformation table) { SichuanCuisine chuan = new SichuanCuisine(dishName,num,degree,orderNum,table.getOrderNum()); this.chuan.add(chuan); } public void addZhejiangCuisine( String dishName, int num, int degree,int orderNum,TableInformation table) { ZhejiangCuisine zhe = new ZhejiangCuisine(dishName,num,degree,orderNum,table.getOrderNum()); this.zhe.add(zhe); } public void removeJinCuisine(JinCuisine jin) { this.jin.remove(jin); } public void removeSichuanCuisine(SichuanCuisine chuan) { this.chuan.remove(chuan); } public void removeZhejiangCuisine(ZhejiangCuisine zhe) { this.zhe.remove(zhe); } } class TableInformation {//桌号信息类 private int orderNum; private LocalDate date; private LocalTime time; private Customer customer = new Customer(); public TableInformation() { } public int getOrderNum() { return orderNum; } public void setOrderNum(int orderNum) { this.orderNum = orderNum; } public LocalDate getDate() { return date; } public void setCustomer(String name,String number){ customer.setNumber(number); customer.setName(name); } public Customer getCustomer() { return customer; } public void setDate(String d) { String[] depositdate = d.split("/",3); int year,month,day; year=Integer.parseInt(depositdate[0]); month=Integer.parseInt(depositdate[1]); day=Integer.parseInt(depositdate[2]); date = LocalDate.of (year,month,day); } public LocalTime getTime() { return time; } public void setTime(String t) { String[] deposittime = t.split("/",3); int hour,minute,second; hour=Integer.parseInt(deposittime[0]); minute=Integer.parseInt(deposittime[1]); second=Integer.parseInt(deposittime[2]); time = LocalTime.of (hour,minute,second); } public boolean ifWeekend(){ boolean judge = false; DayOfWeek week = date.getDayOfWeek(); int weekday = week.getValue(); if(weekday == 6||weekday == 7){ judge = true; } return judge; } public double discount(){ double result = 1.0; // if(dish.getIfSpecial() == false) { LocalTime time1 = LocalTime.of(17, 00, 00); LocalTime time2 = LocalTime.of(20, 30, 00); LocalTime time3 = LocalTime.of(10, 30, 00); LocalTime time4 = LocalTime.of(14, 30, 00); if (ifWeekend() == false) { if ((time.isAfter(time1) && time.isBefore(time2))||time.compareTo(time1) == 0||time.compareTo(time2) == 0) { result = 0.8; } if ((time.isAfter(time3) && time.isBefore(time4))||time.compareTo(time3) == 0||time.compareTo(time4) == 0) { result = 0.6; } } return result; } public boolean ifopen(){ boolean judge = false; LocalTime time1 = LocalTime.of(9, 30, 00); LocalTime time2 = LocalTime.of(21, 30, 00); if(ifWeekend() == false){ if(ifOpenNight() == true){ judge = true; } if(ifOpenNoon() == true){ judge = true; } }else{ if((time.isAfter(time1) && time.isBefore(time2))||time.compareTo(time1) == 0||time.compareTo(time2) == 0){ judge = true; } } return judge; } public boolean ifOpenNight(){ boolean judge = false; LocalTime time1 = LocalTime.of(17, 00, 00); LocalTime time2 = LocalTime.of(20, 30, 00); if((time.isAfter(time1) && time.isBefore(time2))||time.compareTo(time1) == 0||time.compareTo(time2) == 0){ judge = true; } return judge; } public boolean ifOpenNoon(){ boolean judge = false; LocalTime time3 = LocalTime.of(10, 30, 00); LocalTime time4 = LocalTime.of(14, 30, 00); if((time.isAfter(time3) && time.isBefore(time4))||time.compareTo(time3) == 0||time.compareTo(time4) == 0){ judge = true; } return judge; } } class TableNumAndPrice {//存储桌子序号和对于需付金额的类别 private int Ordernum; private double TotalPrice; private double InitialTotalPrice; public double getInitialTotalPrice() { return InitialTotalPrice; } public void setInitialTotalPrice(double initialTotalPrice) { InitialTotalPrice = initialTotalPrice; } public int getOrdernum() { return Ordernum; } public void setOrdernum(int ordernum) { Ordernum = ordernum; } public double getTotalPrice() { return TotalPrice; } public void setTotalPrice(double totalPrice) { TotalPrice = totalPrice; } public TableNumAndPrice() { } public TableNumAndPrice(int ordernum, double totalPrice, double initialTotalPrice){ TotalPrice = totalPrice; InitialTotalPrice = initialTotalPrice; this.Ordernum = ordernum; } } class Delete {//删除桌号类 private int tableNum; private int deleteNum; public Delete() { } public Delete(int tableNum, int deleteNum) { this.tableNum = tableNum; this.deleteNum = deleteNum; } public int getTableNum() { return tableNum; } public void setTableNum(int tableNum) { this.tableNum = tableNum; } public int getDeleteNum() { return deleteNum; } public void setDeleteNum(int deleteNum) { this.deleteNum = deleteNum; } }

1)设计与分析

    我是按照题目要求对类进行了设计。SolveInformation类来处理输入信息。Customer类用于储存顾客的基本信息和他们应支付的金额。CustomerDeposit类用于存储顾客对象,拥有添加、查找的功能。Delete类用于存储在需要删除的点菜记录的序号和该删除记录所在的桌号。Dish类用于存储菜品的基本信息,本次还添加了菜系种类的属性用于判断是否为特殊菜系。Menu类用于存储输入菜谱菜品信息,此次额外增加了判断特殊菜系的添加方法。Order类存储了点菜记录,这次添加了一个存储特殊菜系的点菜记录的方法。Record还是跟之前一样储存点菜记录的基本信息。SpecialRecord类用数组储存了特殊菜系的几个类并拥有各个菜系的平均口味输出方法。OrderOtherDishes类用于储存代点菜的基本信息。SichuanCuisine、JinCuisine、SichuanCuisine三个类则储存了对应特殊菜系的基本信息(包括口味度)。TableInformation类用于储存桌号的基本信息(包括时间)。TableNumAndPrice类用于储存每个桌号对应的初始金额和打完折扣的最终价格。

  在SolveInformation类中的整体思路是先设置桌号中桌子的字符串以及结束输入的字符串和所需类的对象。然后通过循环,先是处理菜谱输入,将添加的程序也跟判断的程序放到一个方法中,采用正则表达式进行判断,再通过if-else来添加菜谱或输出错误情况。接着继续通过循环处理桌号信息和点菜信息,处理方法与上面类似,添加程序也跟判断程序放到一个方法中,除了正则表达式,还通过输入字符串分割后形成的字符串数组的长度进行相关判断,原循环里通过循环嵌套使用这两个方法,并用if-else来判断是否输入了“delete”,并单独将特色菜系的删除语句写出(通过在特殊菜系的储存数组删除元素来实现)。接着使用输出方法,该方法根据输出格式主要采用for循环与if-else嵌套来分别进行输出。

复杂度:

类图:

 

2)遇到的问题与心得

 i.在非table信息输入时,判断信息正误中所使用的的数组越界。在原来table信息的输入前加上字符串是否含“table”的判断即可解决问题。

 心得:在对字符串信息进行识别时,应当抓住其中最特殊的内容来进行判断,这样正确率最高。

 

 ii.辣度超范围,未输出错误提示,也导致计算结果错误。添加特色菜的方法的参数输入顺序弄错,导致口味度与份数的数据传反,将两数据调换位置即可解决问题。

 心得:对于方法的传参顺序,最后还是使用统一的顺序或者都使用自己习惯的顺序。不要差不多的方法,参数传入顺序弄的不一样,很容易因为后续程序传参忘记调整导致错误。

 

 iii.菜的口味度输出有误,因为在输入特色菜数据时,都错误地使用了川菜的add方法,将对应方法改回原特色菜类型的add方法即可。

 心得:在有相似程序,而进行复制粘贴时,不能忘记修改对应的部分语句。

 

 iv.table1应还有浙菜,但并未输出,因为特色菜在删除的序号与别的桌的点菜记录的序号相等时,会删除,导致数据丢失。增加Delete类,类里增加储存Table序号的属性,修改 原有判断语句,增加桌号的判断,即可解决问题。

 心得:在处理数据时应当注意每个数据的适用场景,在判断时也要将适用场景加上,以免不同场景的数据互串。

 

3)改进建议

   方法中拥有多个功能,不是很符合单一职责的原则,可以对方法进行细分,增加方法的种类和数量,使程序层次更清晰。

 2.第八次题目集

 7-1 课程成绩统计程序-1

 

某高校课程从性质上分为:必修课、选修课,从考核方式上分为:考试、考察。

 

考试的总成绩由平时成绩、期末成绩分别乘以权重值得出,比如平时成绩权重0.3,期末成绩权重0.7,总成绩=平时成绩*0.3+期末成绩*0.7。

 

考察的总成绩直接等于期末成绩

 

必修课的考核方式必须为考试,选修课可以选择考试、考察任一考核方式。

 

1、输入:

 

包括课程、课程成绩两类信息。

 

课程信息包括:课程名称、课程性质、考核方式(可选,如果性质是必修课,考核方式可以没有)三个数据项。

 

课程信息格式:课程名称+英文空格+课程性质+英文空格+考核方式

 

课程性质输入项:必修、选修

 

考核方式输入选项:考试、考察

 

课程成绩信息包括:学号、姓名、课程名称、平时成绩(可选)、期末成绩

 

课程信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+平时成绩+英文空格+期末成绩

 

以上信息的相关约束:

 

1)平时成绩和期末成绩的权重默认为0.3、0.7

 

2)成绩是整数,不包含小数部分,成绩的取值范围是【0,100】

 

3)学号由8位数字组成

 

4)姓名不超过10个字符

 

5)课程名称不超过10个字符

 

6)不特别输入班级信息,班级号是学号的前6位。

 

2、输出:

 

输出包含三个部分,包括学生所有课程总成绩的平均分、单门课程成绩平均分、单门课程总成绩平均分、班级所有课程总成绩平均分。

 

为避免误差,平均分的计算方法为累加所有符合条件的单个成绩,最后除以总数。

 

1)学生课程总成绩平均分按学号由低到高排序输出

 

格式:学号+英文空格+姓名+英文空格+总成绩平均分

 

如果某个学生没有任何成绩信息,输出:学号+英文空格+姓名+英文空格+"did not take any exams"

 

2)单门课程成绩平均分分为三个分值:平时成绩平均分(可选)、期末考试平均分、总成绩平均分,按课程名称的字符顺序输出

 

格式:课程名称+英文空格+平时成绩平均分+英文空格+期末考试平均分+英文空格+总成绩平均分

 

如果某门课程没有任何成绩信息,输出:课程名称+英文空格+"has no grades yet"

 

3)班级所有课程总成绩平均分按班级由低到高排序输出

 

格式:班级号+英文空格+总成绩平均分

 

如果某个班级没有任何成绩信息,输出:班级名称+英文空格+ "has no grades yet"

 

异常情况:

 

1)如果解析某个成绩信息时,课程名称不在已输入的课程列表中,输出:学号+英文空格+姓名+英文空格+":"+课程名称+英文空格+"does not exist"

 

2)如果解析某个成绩信息时,输入的成绩数量和课程的考核方式不匹配,输出:学号+英文空格+姓名+英文空格+": access mode mismatch"

 

以上两种情况如果同时出现,按第一种情况输出结果。

 

3)如果解析某个课程信息时,输入的课程性质和课程的考核方式不匹配,输出:课程名称+" : course type & access mode mismatch"

 

4)格式错误以及其他信息异常如成绩超出范围等,均按格式错误处理,输出"wrong format"

 

5)若出现重复的课程/成绩信息,只保留第一个课程信息,忽略后面输入的。

 

信息约束:

 

1)成绩平均分只取整数部分,小数部分丢弃

 

参考类图:

 


image.png

源代码:

import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Locale;
class Main {//重复输入判定还未加
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        String end = "end";//结束的字符串
        ArrayList<Course> courses = new ArrayList<>();//用于储存课程
        ArrayList<Class> classes = new ArrayList<>();//用于储存班级
        ArrayList<CourseSelection> courseSeles = new ArrayList<>();
        Check check = new Check();//用于输入检查
        boolean judge = false;//判断是否重复输入
        String[] deposit = input.split(" ");//储存分割后的字符串
        if (!input.equals(end)) {
            do {
                if (check.coures(input) == 0) {//检查是否输入格式错误
                    for(Course course: courses){
                        if(course.getname().equals(deposit[0]))
                            judge = true;
                    }
                    if(!judge){//对输入的课程信息进行处理
                        Course mCourse = new Course();
                        mCourse.setname(deposit[0]);
                        mCourse.setType(deposit[1]);
                        if (deposit.length != 2) {
                            mCourse.setAssessMeth(deposit[2]);
                        } else {
                            mCourse.setAssessMeth("考试");
                        }
                        courses.add(mCourse);
                    }judge = false;
                } else {
                    if (check.coures(input) == -1) System.out.println("wrong format");
                    if (check.coures(input) == 1)
                        System.out.println(deposit[0] + " : course type & access mode mismatch");
                }
                input = in.nextLine();
                deposit = input.split(" ");
            } while (!input.equals(end) && deposit[0].length() != 8);//检查是否遇到课程成绩信息
            do {
                if (!input.equals(end)) {
                    deposit = input.split(" ");//储存分割后的字符串
                    Class mClass = new Class();//用作媒介
                    CourseSelection courseSele;
                    Course mCourse = new Course();
                    Student mStudent;
                    ExamScores score1;
                    AssessmentScores score2;
                    Score iScore;
                    if (check.grading(input, courses) == 3) {//检查输入信息,结果为正常
                        for(CourseSelection sele: courseSeles){
                            if(sele.getStudent().getId().equals(deposit[0]) && sele.getCourse().getname().equals(deposit[2]))
                                judge = true;
                        }
                        if(!judge){//对输入的课程成绩信息进行处理
                            mClass.setOrder(deposit[0].substring(0, 6));
                            mCourse.setname(deposit[2]);
                            mStudent = new Student(deposit[0],deposit[1]);
                            if (deposit.length == 5) {
                                iScore = new ExamScores();
                                score1 = (ExamScores) iScore;
                                score1.setRGrade(Integer.parseInt(deposit[3]));
                                score1.setFGrade(Integer.parseInt(deposit[4]));
                                courseSele = new CourseSelection(mStudent, score1, mCourse);
                            }else {
                                iScore = new AssessmentScores();
                                score2 = (AssessmentScores) iScore;
                                score2.setFGrade(Integer.parseInt(deposit[3]));
                                courseSele = new CourseSelection(mStudent, score2, mCourse);
                            }
                                courseSeles.add(courseSele);
                                add(classes, check, deposit, mStudent, mClass);
                        }judge = false;
                    } else {
                        if (check.grading(input, courses) == -1) {//输入信息格式错误
                            System.out.println("wrong format");
                        } else {
                            mClass.setOrder(deposit[0].substring(0, 6));
                            mStudent = new Student(deposit[0],deposit[1]);
                            add(classes, check, deposit, mStudent, mClass);
                            if (check.grading(input, courses) == 1) {//输入信息中的课程不存在
                                System.out.println(deposit[2] + " does not exist");
                            } else {
                                if (check.grading(input, courses) == 2) {//输入信息不匹配
                                    System.out.println(deposit[0] + " " + deposit[1] + " : access mode mismatch");
                                }
                            }
                        }
                    }
                    input = in.nextLine();
                }
            } while (!input.equals(end));//检查是否输入结束
            printresult(classes, courseSeles, courses);
        }
    }
    public static void add(ArrayList<Class> classes, Check check, String[] deposit, Student mediumStudent, Class mediumClass) {//添加班级和班级内学生
        if (check.ifExistClass(deposit[0].substring(0, 6), classes) == -1) {
            classes.add(mediumClass);
            classes.get(classes.size() - 1).getStudents().add(mediumStudent);
        } else {
            if (check.ifExistStudent(deposit[0], classes.get(check.ifExistClass(deposit[0].substring(0, 6), classes)).getStudents()) == -1) {
                classes.get(check.ifExistClass(deposit[0].substring(0, 6), classes)).getStudents().add(mediumStudent);
            }
        }
    }
    public static void printresult(ArrayList<Class> classes, ArrayList<CourseSelection> courseSelections, ArrayList<Course> courses) {//用于结尾的输出
        Comparator<Class> claCom = Comparator.comparing(Class::getOrder);//给班级排序
        Comparator<Student> stuCom = Comparator.comparing(Student::getId);//给学生排序
        ArrayList<Integer> claNum = new ArrayList<>();
        int iclaNum = 0;//储存每个班的课程数量
        classes.sort(claCom);
        for (Class aclass : classes) {
            aclass.getStudents().sort(stuCom);
        }
        double sumStuSc = 0,sumClaSc = 0,sumCouSc = 0, numChoice = 0;
        int sumRegrSco = 0, sumFinSc = 0,numCourse = 0;
        boolean judge2 = true;
        Comparator<Course> courseCom = (o1, o2) -> {//给课程排序
            Comparator<Object> comparer = Collator.getInstance(Locale.CHINA);
            return comparer.compare(o1.getname(), o2.getname());
        };
        courses.sort(courseCom);
        for (Class aclass : classes) {
            for (int i = 0; i < aclass.getStudents().size(); i++) {
                for (CourseSelection courseSele : courseSelections) {
                    if (courseSele.getStudent().getId().equals(aclass.getStudents().get(i).getId())) {
                        if (courseSele.getScore().getRScore() != -1) {
                            sumStuSc += courseSele.getScore().getRScore();
                            numCourse++;iclaNum++;
                        }
                        if(courseSele.getStudent().getId().equals(aclass.getStudents().get(i).getId())){
                            judge2 = false;
                        }
                    }
                }
                if(courseSelections.size() == 0)
                    judge2 = true;
                if (!judge2) {
                    sumClaSc += sumStuSc;
                    System.out.printf("%s %s %d\n",aclass.getStudents().get(i).getId(),aclass.getStudents().get(i).getName(),(int)(sumStuSc/numCourse));
                    if (aclass.getScore() == -1)
                        aclass.setScore(sumClaSc);
                    else {
                        aclass.setScore(aclass.getScore() + sumClaSc);
                    }
                } else {
                    System.out.printf("%s %s did not take any exams\n",aclass.getStudents().get(i).getId(),aclass.getStudents().get(i).getName());
                    aclass.getStudents().remove(aclass.getStudents().get(i));
                    i--;
                }judge2 = true;
                sumStuSc =sumClaSc = 0;
                numCourse = 0;
            }
            claNum.add(iclaNum);iclaNum = 0;
        }
        for (Course course : courses) {
            for (CourseSelection courseSele : courseSelections) {
                if (course.getname().equals(courseSele.getCourse().getname())) {
                    if (course.getAssessMeth().equals("考试")) {
                        ExamScores examScores = (ExamScores) courseSele.getScore();
                        sumRegrSco += examScores.getRGrade();
                        sumFinSc += examScores.getFGrade();
                        sumCouSc += examScores.getRScore();
                    } else {
                        AssessmentScores assessScores = (AssessmentScores) courseSele.getScore();
                        sumFinSc += assessScores.getFGrade();
                        sumCouSc += assessScores.getRScore();
                    }
                    numChoice++;
                }
                if(courseSele.getCourse().getname().equals(course.getname())){
                    judge2 = false;
                } }
            int reguScore = (int)(sumRegrSco * 1.0/numChoice);
            int finScore = (int)(sumFinSc * 1.0/numChoice);
            int couSco = (int)(sumCouSc/numChoice);
            if(courseSelections.size() == 0)
                judge2 = true;
            if (!judge2) {
                if (course.getAssessMeth().equals("考试"))
                    System.out.printf("%s %d %d %d\n", course.getname(),reguScore, finScore,couSco);
                else
                    System.out.printf("%s %d %d\n",course.getname(),finScore,couSco);
            } else {
                System.out.println(course.getname() + " has no grades yet");
            }judge2 = true;
            sumFinSc = sumRegrSco = 0;
            sumCouSc = 0;
            numChoice = 0;}
        for (int i = 0;i<classes.size();i++) {
            int claScore =  (int) (classes.get(i).getScore() / claNum.get(i));
            if (classes.get(i).getScore() == -1) {
                System.out.println(classes.get(i).getOrder() + " has no grades yet");
            } else {
                System.out.printf("%s %d\n", classes.get(i).getOrder(),claScore);
            } } }
}

class AssessmentScores extends Score{
    private int fGrade = -1;
    public AssessmentScores() {
    }
    public int getFGrade() {
        return fGrade;
    }
    public void setFGrade(int fGrade) {
        this.fGrade = fGrade;
    }
    public int getRScore(){
        int sum = -1;
        if(ifExistCourseScore()){
            if(fGrade != -1){
                sum = 0;
                sum = (int)fGrade;
            }
        }
        return sum;
    }
    public boolean ifExistCourseScore(){
        return fGrade != -1;
    }
}
class Check {
    public int coures(String deposit) {//判断课程信息是否输入有误
        int judge = 0;
        String[] courseDeposit = deposit.split("[ ]");
        Pattern pattern1 = Pattern.compile("(([1-9])|([a-zA-Z])|([一-龥])){1,10} (必修|选修)( (考试|考察)){0,1}");
        Matcher matcher1 = pattern1.matcher(deposit);
        if (!matcher1.matches()) {
            judge = -1;//输入有误
        } else {
            if (courseDeposit.length != 2) {
                if (courseDeposit[1].equals("必修") && courseDeposit[2].equals("考察")) {
                    judge = 1;
                }
            }else{
                if (courseDeposit[1].equals("选修")) {
                    judge = -1;
                }
            }

        }
        return judge;
    }
    public int grading(String deposit, ArrayList<Course> courses) {//用于判断课程成绩信息输入是否有误
        int judge = 0;
        Pattern pattern1 = Pattern.compile("[1-9][0-9]{7} (([a-zA-Z])|([一-龥])){1,10} (([0-9])|([a-zA-Z])|([一-龥])){1,10} (([0-9]|[1-9][0-9]|100) )?([0-9]|[1-9][0-9]|100)");
        Matcher matcher1 = pattern1.matcher(deposit);
        if (!matcher1.matches()) {
            judge = -1;
        } else {
            String[] gradingDeposit = deposit.split("[ ]");
            if (courses.size() == 0) {
                judge = 1;
            }
            for (Course course : courses) {
                if (course.getname().equals(gradingDeposit[2])) {
                    if (course.getAssessMeth().equals("考试")) {
                        if (gradingDeposit.length < 5) {
                            judge = 2;
                        } else {
                            judge = 3;
                        }
                    } else {
                        if (gradingDeposit.length > 4) {
                            judge = 2;
                        } else {
                            judge = 3;
                        }
                    }
                    break;
                } else {
                    judge = 1;
                }
            }
        }
        return judge;
    }
    public int ifExistClass(String classorder, ArrayList<Class> classes) {
        int judge = -1;
        for (int i = 0; i < classes.size(); i++) {
            if (classes.get(i).getOrder().equals(classorder)) {
                judge = i;
            }
        }
        return judge;
    }
    public int ifExistStudent(String id, ArrayList<Student> students) {
        int judge = -1;
        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getId().equals(id)) {
                judge = i;
            }
        }
        return judge;
    }
}
class Class {//班级类
    private ArrayList<Student> students = new ArrayList<>();
    private String Order;
    private double score = -1;
    public Class() {
    }

    public double getScore() {
        return score;
    }
    public void setScore(double score) {
        this.score = score;
    }
    public String getOrder() {
        return Order;
    }
    public void setOrder(String Order) {
        this.Order = Order;
    }
    public ArrayList<Student> getStudents() {
        return students;
    }
}
class Course {//课程类
    private String name;
    private String Type;
    private String assessMeth;
    public Course() {
    }
    public String getname() {
        return name;
    }
    public void setname(String name) {
        this.name = name;
    }
    public void setType(String Type) {
        this.Type = Type;
    }
    public String getAssessMeth() {
        return assessMeth;
    }
    public void setAssessMeth(String assessMeth) {
        this.assessMeth = assessMeth;
    }
}
class CourseSelection {//选课类
    private Student student = new Student();
    private Score score;
    private Course course = new Course();
    public CourseSelection(Student student,Score score,Course course) {
        this.student = student;
        this.course = course;
        this.score = score;
    }
    public Student getStudent() {
        return student;
    }
    public Score getScore() {
        return score;
    }
    public Course getCourse() {
        return course;
    }
}
class ExamScores extends Score{//考试类
    private int rGrade = -1;
    private int fGrade = -1;
    public ExamScores() {
    }
    public int getRGrade() {
        return rGrade;
    }
    public void setRGrade(int rGrade) {
        this.rGrade = rGrade;
    }
    public int getFGrade() {
        return fGrade;
    }
    public void setFGrade(int fGrade) {
        this.fGrade = fGrade;
    }
    public int getRScore(){
        int sum = -1;
        if(ifExistCourseScore()){
            if(rGrade != -1){
                sum = 0;
                sum = (int)(0.3*rGrade+0.7*fGrade);
            }
        }
        return sum;
    }
    public boolean ifExistCourseScore(){
        return rGrade != -1 || fGrade != -1;
    }
}
abstract class Score {//成绩抽象类
    private int rScore;
    public Score() {
    }
    public int getRScore() {
        return rScore;
    }
}
class Student {//学生类
    private String id;
    private String name;
    public Student() {
    }
    public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

1)设计与分析

 根据类图要求,设置了Class、Course、CourseSelection、Score、AssessmentScore、ExamScore、Student类,此外还添加了Check类用于判断输入数据是否有误。Class类中拥有储存Student的数组、班级号、班级分数这些属性和对应get、set方法。Course类中是拥有课程名称、类型、考察方式作为属性和对应的get、set方法。CourseSelection类中有Student、Score、Course类的对象和对应get方法。Score作为抽象方法有一个最终成绩作为属性,还有其对应get方法。AssessmentScore类是考察成绩,继承Score类,拥有期末考试成绩的属性和并对得到最终成绩的get方法进行重写。ExamScore类与AssessmentScore类相似,只是多了个期中考试成绩的属性,且在最终成绩的get方法中,计算方式有点不同而已,同样继承Score类。Student类则以学生的学号和姓名作为属性,有对应get和set方法。Check中分别有判断课程信息输入和课程成绩信息输入的方法,主要采用正则表达式和分割后字符串对应位置的字符串内容来进行判断。Check中还分别有判断该班级是否存在,该学生是否存在的方法,都采用遍历相关数组的方法来进行判断。

 在Main函数中先创建Class、Course、CourseSelection的对象数组,再创建Check对象用于判断数据是否有误,用一个if语句来排除一开始就直接输入“end”的情况,再用do-While循环处理课程信息,内部使用if-else嵌套,每次分割输入的字符串,进行查重和判断,通过中间对象,将数据放入对应数组。再使用do-While循环处理课程成绩信息,也是用if-else嵌套,进行查重和判断,输出错误提示,通过中间变量储存数据,根据分割后字符串数组的长度来判断创建AssessmentScore类还是ExamScore类对象,最后将这些对象放入对应数组中。输出方法中先是根据题目要求采用Comparator来规定之前创建的对象数组的排序方式,然后进行排序,再进行查重,接着主要通过for循环嵌套和if-else嵌套来进行数据的整合计算和输出。

复杂度:

 

类图:

 

2)遇到的问题与心得

 i.输入格式正常,未输入课程成绩信息,输出错误。因为未在课程输入的循环条件中加上输入不为end的条件,导致end进入了课程信息储存的循环,因不符格式输出wrong format。在该循环的条件中加上input.equals(end) == false即可解决问题。

 心得:对于循环中的条件选取应当考虑多种情况,以免数据错误地进入循环。

 

 ii.出现了错误对象,原因是判断条件中忽略了选修但是考试的情况,导致用考察的分数对象去创建考试的分数对象。将判断条件从判断课程性质,改为判断课程考核方式即可解决问题。

 心得:对于输入数据的类型情况应当考虑的更加全面,来避免漏掉一些情况导致程序出错。

 

 iV.最后输出的班级总成绩平均分偏低,因为在进行班级平均分运算时,学生个数加了两次,将重复相加的语句删掉,即可解决问题

心得:对于数据的运算,要小心数据的再使用,对于每个数据的运算使用应该确保其符合运算逻辑。

 

3)改进建议

 在数据处理上还是有些繁琐,可以采用一些更简单和提出重复或相似部分的方式来简化代码结构。

 3.第九次题目集

 7-1 统计Java程序中关键词的出现次数

 

编写程序统计一个输入的Java源码中关键字(区分大小写)出现的次数。说明如下:

 

  • Java中共有53个关键字(自行百度)
  • 从键盘输入一段源码,统计这段源码中出现的关键字的数量
  • 注释中出现的关键字不用统计
  • 字符串中出现的关键字不用统计
  • 统计出的关键字及数量按照关键字升序进行排序输出
  • 未输入源码则认为输入非法

 

输入格式:

 

输入Java源码字符串,可以一行或多行,以exit行作为结束标志

 

输出格式:

 

  • 当未输入源码时,程序输出Wrong Format
  • 当没有统计数据时,输出为空
  • 当有统计数据时,关键字按照升序排列,每行输出一个关键字及数量,格式为数量\t关键字

源代码:

import java.util.*;
public class Main {
    public static void main(String[] args){
        String str;//用于读取输入
        String[] s = {"abstract","assert","boolean","break","byte","case","catch","char","class","continue","default", "do","double","else","enum","extends","final","finally","float","for","if", "implements","import", "int","interface",
                "instanceof","long","native","new","package","private","protected","public", "return","short","static","strictfp","super","switch","synchronized","this","throw","throws", "transient","try","void","volatile","while","goto","const","true","false","null"
        };//关键词字符串数组
        TreeSet<String> strs = new TreeSet<>();//存储关键字用于查询
        Map<String,Integer> result = new HashMap<>();//存储输出结果
        ArrayList<String> strings = new ArrayList<>();//存储输入的代码
        Scanner in = new Scanner(System.in);
        Collections.addAll(strs, s);//放入关键词
        str = in.nextLine();
        strings.add(str);
        str += "?";//作为每一行的分行符号
        while(str.indexOf("exit") == -1) {
            strings.add(in.nextLine());
            str += (strings.get(strings.size()-1)+ "?");//使输入的代码连成一行
            str = str.replaceAll("\\=","a");//排除输入字符串中有“ =null”的情况
            if(str.indexOf("/*") != -1&&str.indexOf("*/") != -1)//去掉多行注释
                str = str.replaceAll("\\/\\*(\\s|\\S)*\\*\\/"," ");
        }
        String[] deposit1 = str.split("[?]");//按行分割
        for(int i = 0;i<deposit1.length;i++){//去除注释和字符串
            deposit1[i] = deposit1[i].replaceAll("\\/\\/(\\s|\\S)*"," ");
            deposit1[i]= deposit1[i].replaceAll("\"(\\s|\\S)*\""," ");
        }
        for(String d:deposit1){
            d = d.replaceAll("\\W"," ");//使所有非单词符号变为空格
            String[] deposit = d.split(" ");//按空格分割
            int num;
            for(String d2:deposit){
                if(strs.contains(d2)){
                    if(result.containsKey(d2)){//放入map
                        num = result.get(d2)+1;
                        result.put(d2,num);
                    }else{
                        result.put(d2,1);
                    }
                }
            }
        }
        print(strings,result);
    }
    public static void print(ArrayList<String> strings,Map<String,Integer> result){//输出方法
        if(result.size() == 0){//看是否输入有统计数据
            System.out.println("Wrong Format");
        }else{
            Set<String> keySet = result.keySet();
            Object[] depositKey = keySet.toArray();//获取map中关键词数组
            Arrays.sort(depositKey);//给输出结果中的关键词排序
            for(Object s:depositKey){//输出
                System.out.println((int)result.get((String)s)+"\t"+s);
            }
        }
    }
}

1)设计与分析

  因为要识别数据的同时计数,所以首选就是使用HashMap,再用TreeSet来存储关键字,这样查询速度也快。因为注释有多行注释和单行注释,所以我的思路是先将输入的每一行代码串成一行,这样就能很方便地处理多行注释,采用正则表达式,将多行注释部分全部替换为空格。又因为单行注释和字符串不影响别的行,所以还是分行的时候处理比较准确和方便,因此在之前串成一行的时候,在每一行的末尾加上个“?”这样就能在去掉多行注释后,还能准确分行,同样也是把注释内容和字符串内容换成空格。最后再把重新分行后每一行的输入代码中的非单词符号换成空格,最后空格二次分割每一行,再进行关键词的识别,就能精确识别。将识别出来的放入HashMap,利用其会覆盖的原理,更新数据,然后经过循环就能得到最终的HashMap。设置一个输出方法,对最终的HashMap进行遍历输出,就可得到结果。

复杂度:

 

类图:

 

 

2)遇到的问题与心得

 i.正确输入却未辨识出关键词,因为在把各行输入代码变成一行时,未在行末添加辨识符号,导致后面分行的时候出问题,在每一行的行末添加“?”作为辨识符号即可解决问题。

 心得:对于数据的处理还是得留个心眼,切实去了解数据在处理完每一步后的状态,以免出现错误影响后续处理。

 

 

3)改进建议

 有一些步骤可以简化,例如替换非单词字符和单行注释,两者可以放到一起。

 4.第十次题目集

 7-3 课程成绩统计程序-2

 

某高校课程从性质上分为:必修课、选修课、实验课,从考核方式上分为:考试、考察、实验。

 

考试的总成绩由平时成绩、期末成绩分别乘以权重值得出,比如平时成绩权重0.3,期末成绩权重0.7,总成绩=平时成绩*0.3+期末成绩*0.7。

 

考察的总成绩直接等于期末成绩

 

实验的总成绩等于课程每次实验成绩的平均分

 

必修课的考核方式必须为考试,选修课可以选择考试、考察任一考核方式。实验课的成绩必须为实验。

 

1、输入:

 

包括课程、课程成绩两类信息。

 

课程信息包括:课程名称、课程性质、考核方式(可选,如果性质是必修课,考核方式可以没有)三个数据项。

 

课程信息格式:课程名称+英文空格+课程性质+英文空格+考核方式

 

课程性质输入项:必修、选修、实验

 

考核方式输入选项:考试、考察、实验

 

考试/考查课程成绩信息包括:学号、姓名、课程名称、平时成绩(可选)、期末成绩

 

考试/考查课程信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+平时成绩+英文空格+期末成绩

 

实验课程成绩信息包括:学号、姓名、课程名称、实验次数、每次成绩

 

实验次数至少4次,不超过9次

 

实验课程信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+实验次数+英文空格+第一次实验成绩+...+英文空格+最后一次实验成绩

 

以上信息的相关约束:

 

1)平时成绩和期末成绩的权重默认为0.3、0.7

 

2)成绩是整数,不包含小数部分,成绩的取值范围是【0,100】

 

3)学号由8位数字组成

 

4)姓名不超过10个字符

 

5)课程名称不超过10个字符

 

6)不特别输入班级信息,班级号是学号的前6位。

 

2、输出:

 

输出包含三个部分,包括学生所有课程总成绩的平均分、单门课程成绩平均分、单门课程总成绩平均分、班级所有课程总成绩平均分。

 

为避免误差,平均分的计算方法为累加所有符合条件的单个成绩,最后除以总数。

 

1)学生课程总成绩平均分按学号由低到高排序输出

 

格式:学号+英文空格+姓名+英文空格+总成绩平均分

 

如果某个学生没有任何成绩信息,输出:学号+英文空格+姓名+英文空格+"did not take any exams"

 

2)单门课程成绩平均分分为三个分值:平时成绩平均分(可选)、期末考试平均分、总成绩平均分,按课程名称的字符顺序输出

 

考试/考察课程成绩格式:课程名称+英文空格+平时成绩平均分+英文空格+期末考试平均分+英文空格+总成绩平均分

 

实验课成绩格式:课程名称+英文空格+总成绩平均分

 

如果某门课程没有任何成绩信息,输出:课程名称+英文空格+"has no grades yet"

 

3)班级所有课程总成绩平均分按班级由低到高排序输出

 

格式:班级号+英文空格+总成绩平均分

 

如果某个班级没有任何成绩信息,输出:班级名称+英文空格+ "has no grades yet"

 

异常情况:

 

1)如果解析某个成绩信息时,课程名称不在已输入的课程列表中,输出:学号+英文空格+姓名+英文空格+":"+课程名称+英文空格+"does not exist"

 

2)如果解析某个成绩信息时,输入的成绩数量和课程的考核方式不匹配,输出:学号+英文空格+姓名+英文空格+": access mode mismatch"

 

以上两种情况如果同时出现,按第一种情况输出结果。

 

3)如果解析某个课程信息时,输入的课程性质和课程的考核方式不匹配,输出:课程名称+" : course type & access mode mismatch"

 

4)格式错误以及其他信息异常如成绩超出范围等,均按格式错误处理,输出"wrong format"

 

5)若出现重复的课程/成绩信息,只保留第一个课程信息,忽略后面输入的。

 

信息约束:

 

1)成绩平均分只取整数部分,小数部分丢弃

 

参考类图(与第一次相同,其余内容自行补充):

 


e724fa4193aa9ee32e78a68cd96fd6df_22401e04-c501-4b28-bb65-dabe39d374e7.png

源代码:

import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Locale;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        String end = "end";//结束的字符串
        ArrayList<Course> courses = new ArrayList<>();//用于储存课程
        ArrayList<Class> classes = new ArrayList<>();//用于储存班级
        ArrayList<CourseSelection> courseSeles = new ArrayList<>();
        Check check = new Check();//用于输入检查
        boolean judge = false;//判断是否重复输入
        String[] deposit = input.split(" ");//储存分割后的字符串
        if (!input.equals(end)) {
            do {
                if (check.coures(input) == 0) {//检查是否输入格式错误
                    for(Course course: courses){
                        if(course.getname().equals(deposit[0]))
                            judge = true;
                    }
                    if(!judge){//对输入的课程信息进行处理
                        Course mCourse = new Course();
                        mCourse.setname(deposit[0]);
                        mCourse.setType(deposit[1]);
                        if (deposit.length != 2) {
                            mCourse.setAssessMeth(deposit[2]);
                        } else {
                            mCourse.setAssessMeth("考试");
                        }
                        courses.add(mCourse);
                    }judge = false;
                } else {
                    if (check.coures(input) == -1) System.out.println("wrong format");
                    if (check.coures(input) == 1)
                        System.out.println(deposit[0] + " : course type & access mode mismatch");
                }
                input = in.nextLine();
                deposit = input.split(" ");
            } while (!input.equals(end) && deposit[0].length() != 8);//检查是否遇到课程成绩信息
            do {
                if (!input.equals(end)) {
                    deposit = input.split(" ");//储存分割后的字符串
                    Class mClass = new Class();//用作媒介
                    CourseSelection courseSele;
                    Course mCourse = new Course();
                    Student mStudent;
                    ExamScores score1;
                    AssessmentScores score2;
                    Experiment score3;
                    Score iScore;
                    if (check.grading(input, courses) == 3) {//检查输入信息,结果为正常
                        for(CourseSelection sele: courseSeles){
                            if(sele.getStudent().getId().equals(deposit[0]) && sele.getCourse().getname().equals(deposit[2]))
                                judge = true;
                        }
                        if(!judge){//对输入的课程成绩信息进行处理
                            mClass.setOrder(deposit[0].substring(0, 6));
                            mCourse.setname(deposit[2]);
                            mStudent = new Student(deposit[0],deposit[1]);
                            if (deposit.length == 5) {
                                iScore = new ExamScores();
                                score1 = (ExamScores) iScore;
                                score1.setRGrade(Integer.parseInt(deposit[3]));
                                score1.setFGrade(Integer.parseInt(deposit[4]));
                                courseSele = new CourseSelection(mStudent, score1, mCourse);
                            }else {
                                if(deposit.length == 4){
                                    iScore = new AssessmentScores();
                                    score2 = (AssessmentScores) iScore;
                                    score2.setFGrade(Integer.parseInt(deposit[3]));
                                    courseSele = new CourseSelection(mStudent, score2, mCourse);
                                }else{
                                    iScore = new Experiment();
                                    score3 = (Experiment) iScore;
                                    score3.setNum(Integer.parseInt(deposit[3]));
                                    for(int i = 4;i<deposit.length;i++){
                                        score3.getScores().add(Integer.parseInt(deposit[i]));
                                    }
                                    courseSele = new CourseSelection(mStudent, score3, mCourse);
                                }

                            }
                            courseSeles.add(courseSele);
                            add(classes, check, deposit, mStudent, mClass);
                        }judge = false;
                    } else {
                        if (check.grading(input, courses) == -1) {//输入信息格式错误
                            System.out.println("wrong format");
                        } else {
                            mClass.setOrder(deposit[0].substring(0, 6));
                            mStudent = new Student(deposit[0],deposit[1]);
                            add(classes, check, deposit, mStudent, mClass);
                            if (check.grading(input, courses) == 1) {//输入信息中的课程不存在
                                System.out.println(deposit[2] + " does not exist");
                            } else {
                                if (check.grading(input, courses) == 2) {//输入信息不匹配
                                    System.out.println(deposit[0] + " " + deposit[1] + " : access mode mismatch");
                                }
                            }
                        }
                    }
                    input = in.nextLine();
                }
            } while (!input.equals(end));//检查是否输入结束
            printresult(classes, courseSeles, courses);
        }
    }
    public static void add(ArrayList<Class> classes, Check check, String[] deposit, Student mediumStudent, Class mediumClass) {//添加班级和班级内学生
        if (check.ifExistClass(deposit[0].substring(0, 6), classes) == -1) {
            classes.add(mediumClass);
            classes.get(classes.size() - 1).getStudents().add(mediumStudent);
        } else {
            if (check.ifExistStudent(deposit[0], classes.get(check.ifExistClass(deposit[0].substring(0, 6), classes)).getStudents()) == -1) {
                classes.get(check.ifExistClass(deposit[0].substring(0, 6), classes)).getStudents().add(mediumStudent);
            }
        }
    }
    public static void printresult(ArrayList<Class> classes, ArrayList<CourseSelection> courseSelections, ArrayList<Course> courses) {//用于结尾的输出
        Comparator<Class> claCom = Comparator.comparing(Class::getOrder);//给班级排序
        Comparator<Student> stuCom = Comparator.comparing(Student::getId);//给学生排序
        ArrayList<Integer> claNum = new ArrayList<>();
        int iclaNum = 0;//储存每个班的课程数量
        classes.sort(claCom);
        for (Class aclass : classes) {
            aclass.getStudents().sort(stuCom);
        }
        double sumStuSc = 0,sumClaSc = 0,sumCouSc = 0, numChoice = 0;
        int sumRegrSco = 0, sumFinSc = 0,numCourse = 0,eSumSco = 0;
        boolean judge2 = true;
        Comparator<Course> courseCom = (o1, o2) -> {//给课程排序
            Comparator<Object> comparer = Collator.getInstance(Locale.CHINA);
            return comparer.compare(o1.getname(), o2.getname());
        };
        courses.sort(courseCom);
        for (Class aclass : classes) {//输出学生数据处理结果
            for (int i = 0; i < aclass.getStudents().size(); i++) {
                for (CourseSelection courseSele : courseSelections) {
                    if (courseSele.getStudent().getId().equals(aclass.getStudents().get(i).getId())) {
                        if (courseSele.getScore().getRScore() != -1) {
                            sumStuSc += courseSele.getScore().getRScore();
                            numCourse++;iclaNum++;
                        }
                        if(courseSele.getStudent().getId().equals(aclass.getStudents().get(i).getId())){
                            judge2 = false;
                        }
                    }
                }
                if(courseSelections.size() == 0)
                    judge2 = true;
                if (!judge2) {
                    sumClaSc += sumStuSc;
                    System.out.printf("%s %s %d\n",aclass.getStudents().get(i).getId(),aclass.getStudents().get(i).getName(),(int)(sumStuSc/numCourse));
                    if (aclass.getScore() == -1)
                        aclass.setScore(sumClaSc);
                    else {
                        aclass.setScore(aclass.getScore() + sumClaSc);
                    }
                } else {
                    System.out.printf("%s %s did not take any exams\n",aclass.getStudents().get(i).getId(),aclass.getStudents().get(i).getName());
                    aclass.getStudents().remove(aclass.getStudents().get(i));
                    i--;
                }judge2 = true;
                sumStuSc =sumClaSc = 0;
                numCourse = 0;
            }
            claNum.add(iclaNum);iclaNum = 0;
        }
        for (Course course : courses) {//输出课程成绩
            for (CourseSelection courseSele : courseSelections) {
                if (course.getname().equals(courseSele.getCourse().getname())) {
                    if (course.getAssessMeth().equals("考试")) {
                        ExamScores examScores = (ExamScores) courseSele.getScore();
                        sumRegrSco += examScores.getRGrade();
                        sumFinSc += examScores.getFGrade();
                        sumCouSc += examScores.getRScore();
                    } else {
                        if(course.getAssessMeth().equals("考察")){
                            AssessmentScores assessScores = (AssessmentScores) courseSele.getScore();
                            sumFinSc += assessScores.getFGrade();
                            sumCouSc += assessScores.getRScore();
                        }else{
                            Experiment eScore = (Experiment) courseSele.getScore();
                            eSumSco += eScore.getRScore();
                        }

                    }
                    numChoice++;
                }
                if(courseSele.getCourse().getname().equals(course.getname())){
                    judge2 = false;
                }
            }
            int reguScore = (int)(sumRegrSco * 1.0/numChoice);
            int finScore = (int)(sumFinSc * 1.0/numChoice);
            int couSco = (int)(sumCouSc/numChoice);
            int rESco = (int)(eSumSco/numChoice);

            if(courseSelections.size() == 0)
                judge2 = true;
            if (!judge2) {
                if (course.getAssessMeth().equals("考试"))
                    System.out.printf("%s %d %d %d\n", course.getname(),reguScore, finScore,couSco);
                else
                if (course.getAssessMeth().equals("考察"))
                    System.out.printf("%s %d %d\n",course.getname(),finScore,couSco);
                else
                    System.out.printf("%s %d\n",course.getname(),rESco);
            } else {
                System.out.println(course.getname() + " has no grades yet");
            }judge2 = true;
            sumFinSc = sumRegrSco = 0;
            sumCouSc = 0;
            numChoice = 0;eSumSco = 0;
        }
        for (int i = 0;i<classes.size();i++) {//输出班级成绩
            int claScore =  (int) (classes.get(i).getScore() / claNum.get(i));
            if (classes.get(i).getScore() == -1) {
                System.out.println(classes.get(i).getOrder() + " has no grades yet");
            } else {
                System.out.printf("%s %d\n", classes.get(i).getOrder(),claScore);
            }
        }
    }

}

class AssessmentScores extends Score {//考察成绩类
    private int fGrade = -1;
    public AssessmentScores() {
    }
    public int getFGrade() {
        return fGrade;
    }
    public void setFGrade(int fGrade) {
        this.fGrade = fGrade;
    }
    public int getRScore(){
        int sum = -1;
        if(ifExistCourseScore()){
            if(fGrade != -1){
                sum = 0;
                sum = (int)fGrade;
            }
        }
        return sum;
    }
    public boolean ifExistCourseScore(){
        return fGrade != -1;
    }
}
class Check {
    public int coures(String deposit) {//判断课程信息是否输入有误
        int judge = 0;
        String[] courseDeposit = deposit.split("[ ]");
        Pattern pattern1 = Pattern.compile("(([0-9])|([a-zA-Z])|([一-龥])){1,10} (必修|选修|实验)( (考试|考察|实验)){0,1}");
        Matcher matcher1 = pattern1.matcher(deposit);
        if (!matcher1.matches()) {
            judge = -1;//输入有误
        } else {
            if (courseDeposit.length != 2) {
                if ((courseDeposit[1].equals("必修") && !courseDeposit[2].equals("考试"))||(courseDeposit[2].equals("实验")&&!courseDeposit[1].equals("实验"))||(courseDeposit[2].equals("考察")&&courseDeposit[1].equals("实验"))) {
                    judge = -1;
                }
            }else{
                if (courseDeposit[1].equals("选修")||courseDeposit[1].equals("实验")) {
                    judge = -1;
                }
            }

        }
        return judge;
    }
    public int grading(String deposit, ArrayList<Course> courses) {//用于判断课程成绩信息输入是否有误
        int judge = 0;
        Pattern pattern1 = Pattern.compile("[1-9][0-9]{7} (([a-zA-Z])|([一-龥])){1,10} (([a-zA-Z])|([一-龥])){1,10} (([0-9]|[1-9][0-9]|100) )?([0-9]|[1-9][0-9]|100)");
        Matcher matcher1 = pattern1.matcher(deposit);
        Pattern pattern2 = Pattern.compile("[1-9][0-9]{7} (([a-zA-Z])|([一-龥])){1,10} (([a-zA-Z])|([一-龥])){1,10} ([4-9])( ([0-9]|[1-9][0-9]|100))*");
        Matcher matcher2 = pattern2.matcher(deposit);
        if (!matcher1.matches()&&!matcher2.matches()) {
            judge = -1;
        } else {

            String[] gradingDeposit = deposit.split("[ ]");
            if (courses.size() == 0) {
                judge = 1;
            }
            for (Course course : courses) {
                if (course.getname().equals(gradingDeposit[2])) {
                    if (course.getAssessMeth().equals("考试")) {
                        if (gradingDeposit.length < 5) {
                            judge = 2;
                        } else {
                            judge = 3;
                        }
                    } else {
                        if (course.getAssessMeth().equals("考察")){
                            if (gradingDeposit.length > 4) {
                                judge = 2;
                            } else {
                                judge = 3;
                            }
                        }else{
                            if(Integer.parseInt(gradingDeposit[3])<4||Integer.parseInt(gradingDeposit[3])>9){
                                judge = -1;
                            }else{
                                if(gradingDeposit.length != (Integer.parseInt(gradingDeposit[3])+4)){
                                    judge = 2;
                                }else{
                                    judge = 3;
                                }
                            }

                        }
                    }
                    break;
                } else {
                    judge = 1;
                }
            }
        }
        return judge;
    }
    public int ifExistClass(String classorder, ArrayList<Class> classes) {
        int judge = -1;
        for (int i = 0; i < classes.size(); i++) {
            if (classes.get(i).getOrder().equals(classorder)) {
                judge = i;
            }
        }
        return judge;
    }
    public int ifExistStudent(String id, ArrayList<Student> students) {
        int judge = -1;
        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getId().equals(id)) {
                judge = i;
            }
        }
        return judge;
    }
}
class Class {//班级类
    private ArrayList<Student> students = new ArrayList<>();
    private String Order;
    private double score = -1;
    public Class() {
    }
    public double getScore() {
        return score;
    }
    public void setScore(double score) {
        this.score = score;
    }
    public String getOrder() {
        return Order;
    }
    public void setOrder(String Order) {
        this.Order = Order;
    }
    public ArrayList<Student> getStudents() {
        return students;
    }

}
class Course {//课程类
    private String name;
    private String Type;
    private String assessMeth;
    public Course() {
    }
    public String getname() {
        return name;
    }
    public void setname(String name) {
        this.name = name;
    }
    public void setType(String Type) {
        this.Type = Type;
    }
    public String getAssessMeth() {
        return assessMeth;
    }
    public void setAssessMeth(String assessMeth) {
        this.assessMeth = assessMeth;
    }

}
class CourseSelection {//选课类
    private Student student = new Student();
    private Score score;
    private Course course = new Course();
    public CourseSelection(Student student,Score score,Course course) {
        this.student = student;
        this.course = course;
        this.score = score;
    }
    public Student getStudent() {
        return student;
    }
    public Score getScore() {
        return score;
    }
    public Course getCourse() {
        return course;
    }

}
class ExamScores extends Score {//考试类
    private int rGrade = -1;
    private int fGrade = -1;
    public ExamScores() {
    }
    public int getRGrade() {
        return rGrade;
    }
    public void setRGrade(int rGrade) {
        this.rGrade = rGrade;
    }
    public int getFGrade() {
        return fGrade;
    }
    public void setFGrade(int fGrade) {
        this.fGrade = fGrade;
    }
    public int getRScore(){
        int sum = -1;
        if(ifExistCourseScore()){
            if(rGrade != -1){
                sum = 0;
                sum = (int)(0.3*rGrade+0.7*fGrade);
            }
        }
        return sum;
    }
    public boolean ifExistCourseScore(){
        return rGrade != -1 || fGrade != -1;
    }

}
class Experiment extends Score{//实验类
    private int num;
    private ArrayList<Integer> scores = new ArrayList<>();

    public Experiment() {
    }
    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public ArrayList<Integer> getScores() {
        return scores;
    }

    public void setScores(ArrayList<Integer> scores) {
        this.scores = scores;
    }
    public int getRScore(){
        int result = 0;
        for(int d:scores){
            result += d;
        }
        result = result/scores.size();
        return result;
    }

}
abstract class Score {//成绩抽象类
    private int rScore;

    public Score() {
    }

    public abstract int getRScore();

}
class Student {//学生类
    private String id;
    private String name;
    public Student() {
    }
    public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

1)设计与分析

  在迭代前题目的基础上,是加了Experiment类,包含该实验课的成绩数量和一个用于储存成绩的数组,同样继承Score类。在Check类的判断方法中更改了正则表达式,添加了if-else中实验的相关判断。在Main类中增加了if-else和for循环语句,使得实验课课程信息和课程成绩信息也能够添加进去,还增加了错误输入时输出的错误提示语句。在Main类的输出方法中添加了Experiment类对象的中间变量和储存实验课成绩的中间变量,新增了实验课成绩输出语句。其余与迭代前题目的设计思路和方法使用一致。

复杂度: 

 

类图:

 

2)遇到的问题与心得

 i.成绩数量不符,却正常输出,因为在检查实验的课程成绩输入时,所需成绩的个数计算有误,字符串分割后的长度忘记加上4本身的这一个长度,导致所需成绩少了一个,使其能够通过检查。在判断语句中加1即可解决问题。

 心得:对于分割后数组长度的把握还是要去验证,以免位置找错,导致数据处理错误。

 

 ii.课程成绩输入不满足实验课程的要求,却未输出wrong form,因为在判断格式时,因为其它课程一同判断的原因,漏了判断输入满足其它课程但不满足实验课程要求的情况,在后续判断中加上相关判断语句即可解决问题。

 心得:对于数据的各种输入情况要想的周全,以免出现遗漏导致输出错误的情况。

 

3)改进建议

 对于多次if-else嵌套和循环,可以考虑进行简化,包括循环。还有就是重复代码有点多可以提取简化。

 5.第十一次题目集

 7-2 课程成绩统计程序-3

 

要求:修改类结构,将成绩类的继承关系改为组合关系,成绩信息由课程成绩类和分项成绩类组成,课程成绩类组合分项成绩类,分项成绩类由成绩分值和权重两个属性构成。

 

完成课程成绩统计程序-2、3两次程序后,比较继承和组合关系的区别。思考一下哪一种关系运用上更灵活,更能够适应变更。

 

题目最后的参考类图未做修改,大家根据要求自行调整,以下内容加粗字体显示的内容为本次新增的内容。

 

某高校课程从性质上分为:必修课、选修课、实验课,从考核方式上分为:考试、考察、实验。

 

考试的总成绩由平时成绩、期末成绩分别乘以权重值得出,比如平时成绩权重0.3,期末成绩权重0.7,总成绩=平时成绩*0.3+期末成绩*0.7。

 

考察的总成绩直接等于期末成绩

 

实验的总成绩等于课程每次实验成绩乘以权重后累加而得。

 

课程权重值在录入课程信息时输入。(注意:所有分项成绩的权重之和应当等于1)

 

必修课的考核方式必须为考试,选修课可以选择考试、考察任一考核方式。实验课的成绩必须为实验。

 

1、输入:

 

包括课程、课程成绩两类信息。

 

课程信息包括:课程名称、课程性质、考核方式、分项成绩数量、每个分项成绩的权重。

 

考试课信息格式:课程名称+英文空格+课程性质+英文空格+考核方式+英文空格+平时成绩的权重+英文空格+期末成绩的权重

 

考察课信息格式:课程名称+英文空格+课程性质+英文空格+考核方式

 

实验课程信息格式:课程名称+英文空格+课程性质+英文空格+考核方式+英文空格+分项成绩数量n+英文空格+分项成绩1的权重+英文空格+。。。+英文空格+分项成绩n的权重

 

实验次数至少4次,不超过9次

 

课程性质输入项:必修、选修、实验

 

考核方式输入选项:考试、考察、实验

 

考试/考查课程成绩信息包括:学号、姓名、课程名称、平时成绩(可选)、期末成绩

 

考试/考查课程成绩信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+平时成绩+英文空格+期末成绩

 

实验课程成绩信息包括:学号、姓名、课程名称、每次成绩{在系列-2的基础上去掉了(实验次数),实验次数要和实验课程信息中输入的分项成绩数量保持一致}

 

实验课程信息格式:学号+英文空格+姓名+英文空格+课程名称+英文空格+第一次实验成绩+...+英文空格+最后一次实验成绩

 

以上信息的相关约束:

 

1)成绩是整数,不包含小数部分,成绩的取值范围是【0,100】

 

2)学号由8位数字组成

 

3)姓名不超过10个字符

 

4)课程名称不超过10个字符

 

5)不特别输入班级信息,班级号是学号的前6位。

 

2、输出:

 

输出包含三个部分,包括学生所有课程总成绩的平均分、单门课程总成绩平均分、班级所有课程总成绩平均分。

 

为避免四舍五入误差,

 

计算单个成绩时,分项成绩乘以权重后要保留小数位,计算总成绩时,累加所有分项成绩的权重分以后,再去掉小数位。

 

学生总成绩/整个班/课程平均分的计算方法为累加所有符合条件的单个成绩,最后除以总数。

 

1)学生课程总成绩平均分按学号由低到高排序输出

 

格式:学号+英文空格+姓名+英文空格+总成绩平均分

 

如果某个学生没有任何成绩信息,输出:学号+英文空格+姓名+英文空格+"did not take any exams"

 

2)单门课程成绩按课程名称的字符顺序输出

 

课程成绩输出格式:课程名称+英文空格+总成绩平均分

 

如果某门课程没有任何成绩信息,输出:课程名称+英文空格+"has no grades yet"

 

3)班级所有课程总成绩平均分按班级由低到高排序输出

 

格式:班级号+英文空格+总成绩平均分

 

如果某个班级没有任何成绩信息,输出:班级名称+英文空格+ "has no grades yet"

 

异常情况:

 

1)如果解析某个成绩信息时,课程名称不在已输入的课程列表中,输出:学号+英文空格+姓名+英文空格+":"+课程名称+英文空格+"does not exist"

 

2)如果解析某个成绩信息时,输入的成绩数量和课程的考核方式不匹配,输出:学号+英文空格+姓名+英文空格+": access mode mismatch"

 

以上两种情况如果同时出现,按第一种情况输出结果。

 

3)如果解析某个课程信息时,输入的课程性质和课程的考核方式不匹配,输出:课程名称+" : course type & access mode mismatch"

 

4)格式错误以及其他信息异常如成绩超出范围等,均按格式错误处理,输出"wrong format"

 

5)若出现重复的课程/成绩信息,只保留第一个课程信息,忽略后面输入的。

 

6)如果解析实验课程信息时,输入的分项成绩数量值和分项成绩权重的个数不匹配,输出:课程名称+" : number of scores does not match"

 

7)如果解析考试课、实验课时,分项成绩权重值的总和不等于1,输出:课程名称+" : weight value error"

 

信息约束:

 

1)成绩平均分只取整数部分,小数部分丢弃

 

参考类图(与第一次相同,其余内容自行补充):

 

fdada4ca193119ee30531ab82ffebbfa_9dbcf4e8-1627-4cf6-8764-cccf44947e2a.png

源代码:

import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Locale;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        String end = "end";//结束的字符串
        ArrayList<Course> courses = new ArrayList<>();//用于储存课程
        ArrayList<Class> classes = new ArrayList<>();//用于储存班级
        ArrayList<CourseSelection> courseSeles = new ArrayList<>();
        ArrayList<ClassScore> cScores  = new ArrayList<>();
        Check check = new Check();//用于输入检查
        boolean judge = false;//判断是否重复输入
        String[] deposit = input.split(" ");//储存分割后的字符串
        if (!input.equals(end)) {
            do {
                ClassScore cSco = new ClassScore();
                if (check.coures(input) == 0) {//检查是否输入格式错误
                    for(Course course: courses){
                        if(course.getname().equals(deposit[0]))
                            judge = true;
                    }
                    if(!judge){//对输入的课程信息进行处理
                        Course mCourse = new Course();
                        mCourse.setname(deposit[0]);
                        mCourse.setType(deposit[1]);
                        if (deposit.length != 4) {
                            mCourse.setAssessMeth(deposit[2]);
                            if(deposit[2].equals("考试")){//设置考试权重
                                cSco.getEmScore().getFGrade().setWeight(Double.parseDouble(deposit[4]));
                                cSco.getEmScore().getRGrade().setWeight(Double.parseDouble(deposit[3]));
                            }
                            if(deposit[2].equals("实验")){//设置实验权重
                                    for(int i = 4;i<deposit.length;i++){
                                        Score s = new Score();
                                        s.setWeight(Double.parseDouble(deposit[i]));
                                        cSco.getEpScore().getScores().add(s);
                                    }
                                mCourse.setScoNum(Integer.parseInt(deposit[3]));
                                }
                        }
                        cScores.add(cSco);
                        courses.add(mCourse);
                    }judge = false;
                } else {
                    if(check.coures(input) == 2) System.out.println(deposit[0]+" : number of scores does not match");
                    if (check.coures(input) == -1) System.out.println("wrong format");
                    if (check.coures(input) == 1)
                        System.out.println(deposit[0] + " : course type & access mode mismatch");
                    if (check.coures(input) == 4)
                        System.out.println(deposit[0] + " : weight value error");
                }
                input = in.nextLine();
                deposit = input.split(" ");
            } while (!input.equals(end) && deposit[0].length() != 8);//检查是否遇到课程成绩信息
            do {
                if (!input.equals(end)) {
                    deposit = input.split(" ");//储存分割后的字符串
                    Class mClass = new Class();//用作媒介
                    Course mCourse = new Course();
                    Student mStudent;
                    if (check.grading(input,courses) == 3) {//检查输入信息,结果为正常
                        for(CourseSelection sele: courseSeles){
                            if(sele.getStudent().getId().equals(deposit[0]) && sele.getCourse().getname().equals(deposit[2]))
                                judge = true;
                        }
                        if(!judge){//对输入的课程成绩信息进行处理
                          int xy = 0;
                           for(int i = 0;i<courses.size();i++){
                               if(deposit[2].equals(courses.get(i).getname())){
                                   xy = i;break;
                               }
                           }
                            CourseSelection courseSele = new CourseSelection();
                            mClass.setOrder(deposit[0].substring(0, 6));
                            mCourse.setname(deposit[2]);
                            mStudent = new Student(deposit[0],deposit[1]);
                            if (deposit.length == 5) {
                                ClassScore cScore1 = new ClassScore();
                                cScore1.getEmScore().getFGrade().setWeight(cScores.get(xy).getEmScore().getFGrade().getWeight());
                                cScore1.getEmScore().getRGrade().setWeight(cScores.get(xy).getEmScore().getRGrade().getWeight());
                                cScore1.getEmScore().setRGrade(Integer.parseInt(deposit[3]));
                                cScore1.getEmScore().setFGrade(Integer.parseInt(deposit[4]));
                                courseSele.setStudent(mStudent);courseSele.setScore(cScore1);courseSele.setCourse(mCourse);
                            }else {
                                if(deposit.length == 4){
                                    ClassScore cScore2 = new ClassScore();
                                    cScore2.getaScore().getFGrade().setWeight(cScores.get(xy).getaScore().getFGrade().getWeight());
                                    cScore2.getaScore().setFGrade(Integer.parseInt(deposit[3]));
                                    courseSele.setStudent(mStudent);courseSele.setScore(cScore2);courseSele.setCourse(mCourse);
                                }else{
                                    ClassScore epSco = new ClassScore();
                                    for(int i = 0;i<deposit.length-3;i++){
                                        Score scoreEp = new Score();
                                        scoreEp.setWeight(cScores.get(xy).getEpScore().getScores().get(i).getWeight());
                                      epSco.getEpScore().getScores().add(scoreEp);
                                        epSco.getEpScore().getScores().get(i).setScore(Integer.parseInt(deposit[i+3]));
                                    }
                                    courseSele.setStudent(mStudent);courseSele.setScore(epSco);courseSele.setCourse(mCourse);
                                }
                            }
                            courseSeles.add(courseSele);
                            add(classes, check, deposit, mStudent, mClass);
                        }judge = false;
                    } else {
                        if (check.grading(input, courses) == -1) {//输入信息格式错误
                            System.out.println("wrong format");
                        } else {
                            mClass.setOrder(deposit[0].substring(0, 6));
                            mStudent = new Student(deposit[0],deposit[1]);
                            add(classes, check, deposit, mStudent, mClass);
                            if (check.grading(input, courses) == 1) {//输入信息中的课程不存在
                               System.out.println(deposit[2] + " does not exist");
                        
                            } else {
                                if (check.grading(input, courses) == 2) {//输入信息不匹配
                                    System.out.println(deposit[0] + " " + deposit[1] + " : access mode mismatch");
                                }
                            }
                        }
                    }
                    input = in.nextLine();
                }
            } while (!input.equals(end));//检查是否输入结束
            printresult(classes, courseSeles, courses);
        }
    }
    public static void add(ArrayList<Class> classes, Check check, String[] deposit, Student mediumStudent, Class mediumClass) {//添加班级和班级内学生
        if (check.ifExistClass(deposit[0].substring(0, 6), classes) == -1) {
            classes.add(mediumClass);
            classes.get(classes.size() - 1).getStudents().add(mediumStudent);
        } else {
            if (check.ifExistStudent(deposit[0], classes.get(check.ifExistClass(deposit[0].substring(0, 6), classes)).getStudents()) == -1) {
                classes.get(check.ifExistClass(deposit[0].substring(0, 6), classes)).getStudents().add(mediumStudent);
            }
        }
    }
    public static void printresult(ArrayList<Class> classes, ArrayList<CourseSelection> courseSelections, ArrayList<Course> courses) {//用于结尾的输出
        Comparator<Class> claCom = Comparator.comparing(Class::getOrder);//给班级排序
        Comparator<Student> stuCom = Comparator.comparing(Student::getId);//给学生排序
        ArrayList<Integer> claNum = new ArrayList<>();
        int iclaNum = 0;//储存每个班的课程数量
        classes.sort(claCom);
        for (Class aclass : classes) {
            aclass.getStudents().sort(stuCom);
        }
        double sumStuSc = 0,sumClaSc = 0,sumCouSc = 0, numChoice = 0;
        int sumRegrSco = 0, sumFinSc = 0,numCourse = 0,eSumSco = 0;
        boolean judge2 = true;
        Comparator<Course> courseCom = (o1, o2) -> {//给课程排序        
            return comparer.compare(o1.getname(), o2.getname());
        };
        courses.sort(courseCom);
        for (Class aclass : classes) {//输出学生成绩信息
            for (int i = 0; i < aclass.getStudents().size(); i++) {
                for (CourseSelection courseSele : courseSelections) {
                    if(courseSele.getScore().ifaScore()){//有考察分数时
                        if (courseSele.getStudent().getId().equals(aclass.getStudents().get(i).getId())) {
                            if (courseSele.getScore().getaScore().getRScore() != -1) {
                                sumStuSc += courseSele.getScore().getaScore().getRScore();
                                numCourse++;iclaNum++;
                            }
                        }
                    }else{
                        if(courseSele.getScore().ifemScore()){//有考试分数时
                            if (courseSele.getStudent().getId().equals(aclass.getStudents().get(i).getId())) {
                                if (courseSele.getScore().getEmScore().getRScore() != -1) {
                                    sumStuSc += courseSele.getScore().getEmScore().getRScore();
                                    numCourse++;iclaNum++;
                                }
                            }
                        }else{//有实验分数时
                            if (courseSele.getStudent().getId().equals(aclass.getStudents().get(i).getId())) {
                                if (courseSele.getScore().getEpScore().getRScore() != -1) {
                                    sumStuSc += courseSele.getScore().getEpScore().getRScore();
                                    numCourse++;iclaNum++;
                                }
                            }
                        }
                    }
                    if(courseSele.getStudent().getId().equals(aclass.getStudents().get(i).getId())){
                        judge2 = false;
                    }
                }
                if(courseSelections.size() == 0)
                    judge2 = true;
                if (!judge2) {
                    sumClaSc += sumStuSc;
                    System.out.printf("%s %s %d\n",aclass.getStudents().get(i).getId(),aclass.getStudents().get(i).getName(),(int)(sumStuSc/numCourse));
                    if (aclass.getScore() == -1)
                        aclass.setScore(sumClaSc);
                    else {
                        aclass.setScore(aclass.getScore() + sumClaSc);
                    }
                } else {
                    System.out.printf("%s %s did not take any exams\n",aclass.getStudents().get(i).getId(),aclass.getStudents().get(i).getName());
                    aclass.getStudents().remove(aclass.getStudents().get(i));
                    i--;
                }judge2 = true;
                sumStuSc =sumClaSc = 0;
                numCourse = 0;
            }
            claNum.add(iclaNum);iclaNum = 0;
        }
        for (Course course : courses) {//输出课程成绩信息
            for (CourseSelection courseSele : courseSelections) {
                if (course.getname().equals(courseSele.getCourse().getname())) {
                    if (course.getAssessMeth().equals("考试")) {
                        sumRegrSco += courseSele.getScore().getEmScore().getRGrade().getScore();
                        sumFinSc += courseSele.getScore().getEmScore().getFGrade().getScore();
                        sumCouSc += courseSele.getScore().getEmScore().getRScore();
                    } else {
                        if(course.getAssessMeth().equals("考察")){
                            sumFinSc += courseSele.getScore().getaScore().getFGrade().getScore();
                            sumCouSc += courseSele.getScore().getaScore().getRScore();
                        }else{
                            eSumSco +=  courseSele.getScore().getEpScore().getRScore();
                        }
                    }
                    numChoice++;
                }
                if(courseSele.getCourse().getname().equals(course.getname())){
                    judge2 = false;
                }
            }
            int reguScore = (int)(sumRegrSco * 1.0/numChoice);
            int finScore = (int)(sumFinSc * 1.0/numChoice);
            int couSco = (int)(sumCouSc/numChoice);
            int rESco = (int)(eSumSco/numChoice);
            if(courseSelections.size() == 0)
                judge2 = true;
            if (!judge2) {
                if (course.getAssessMeth().equals("考试"))
                    System.out.printf("%s %d\n", course.getname(),couSco);
                else
                if (course.getAssessMeth().equals("考察"))
                    System.out.printf("%s %d\n",course.getname(),couSco);
                    else
                    System.out.printf("%s %d\n",course.getname(),rESco);
            } else {
                System.out.println(course.getname() + " has no grades yet");
            }judge2 = true;
            sumFinSc = sumRegrSco = 0;
            sumCouSc = 0;
            numChoice = 0;eSumSco = 0;
        }
        for (int i = 0;i<classes.size();i++) {
            int claScore =  (int) (classes.get(i).getScore() / claNum.get(i));
            if (classes.get(i).getScore() == -1) {
                System.out.println(classes.get(i).getOrder() + " has no grades yet");
            } else {
                System.out.printf("%s %d\n", classes.get(i).getOrder(),claScore);
            }
        }
    }
}
class AssessmentScores{//考察成绩类
    private Score fGrade = new Score();
    public AssessmentScores() {
    }
    public Score getFGrade() {
        return fGrade;
    }
    public void setFGrade(int fGrade) {
        this.fGrade.setScore(fGrade);
    }
    public int getRScore(){//总成绩
        int sum = -1;
        if(ifExistCourseScore()){
            if(fGrade.getScore() != -1){
                sum = 0;
                sum = (int)fGrade.getScore();
            }
        }
        return sum;
    }
    public boolean ifExistCourseScore(){
        return fGrade.getScore() != -1;
    }
}
class Check {
    public int coures(String deposit) {//判断课程信息是否输入有误
        int judge = 0;
        String[] courseDeposit = deposit.split("[ ]");
        Pattern pattern1 = Pattern.compile("(([0-9])|([a-zA-Z])|([一-龥])){1,10} (必修|选修|实验) (考试|考察|实验)( [4-9])?( 0\\.([0-9]+))*");
        Matcher matcher1 = pattern1.matcher(deposit);
        if (!matcher1.matches()) {
            judge = -1;//输入有误
        } else {
            if (courseDeposit.length != 4) {
                if ((courseDeposit[1].equals("必修") && !courseDeposit[2].equals("考试"))||(courseDeposit[2].equals("实验")&&!courseDeposit[1].equals("实验"))||(courseDeposit[2].equals("考察")&&courseDeposit[1].equals("实验"))) {
                    judge = 1;
                }
                if((courseDeposit[1].equals("必修") && courseDeposit.length!=5)||(courseDeposit[1].equals("选修") && courseDeposit.length!=3)){
                    judge = -1;
                }
            }else{
                if (courseDeposit[1].equals("选修")||courseDeposit[1].equals("实验")) {
                    judge = -1;
                }
                if(courseDeposit[2].equals("考试")){
                    judge = -1;
                }
            }
        }

        if(judge != -1&&judge != 1){
            if(courseDeposit.length == 4){
                if(Double.parseDouble(courseDeposit[2])+Double.parseDouble(courseDeposit[3]) != 1){
                    judge = 4;
                }
            }else{
                if(courseDeposit.length == 5){
                    if(Double.parseDouble(courseDeposit[3])+Double.parseDouble(courseDeposit[4]) != 1){
                        judge = 4;
                    }
                }
                if(courseDeposit.length > 5){
                    if(courseDeposit.length != Integer.parseInt(courseDeposit[3])+4){
                        judge = 2;
                    }else{
                        double sum = 0;
                        for(int i = 4;i<courseDeposit.length;i++){
                            sum += Double.parseDouble(courseDeposit[i]);
                        }
                        if(sum != 1){
                            judge = 4;
                        }
                    }
                }
            }
        }
        return judge;
    }
    public int grading(String deposit, ArrayList<Course> courses) {//用于判断课程成绩信息输入是否有误
        int judge = 0;
        Pattern pattern1 = Pattern.compile("[1-9][0-9]{7} (([a-zA-Z])|([一-龥])){1,10} (([a-zA-Z])|([一-龥])){1,10} (([0-9]|[1-9][0-9]|100) )?([0-9]|[1-9][0-9]|100)");
        Matcher matcher1 = pattern1.matcher(deposit);
        Pattern pattern2 = Pattern.compile("[1-9][0-9]{7} (([a-zA-Z])|([一-龥])){1,10} (([a-zA-Z])|([一-龥])){1,10}( ([0-9]|[1-9][0-9]|100))+");
        Matcher matcher2 = pattern2.matcher(deposit);
        if (!matcher1.matches()&&!matcher2.matches()) {
            judge = -1;
        } else {
            String[] gradingDeposit = deposit.split(" ");
            if (courses.size() == 0) {
                judge = 1;
            }
            for (Course course : courses) {
                if (course.getname().equals(gradingDeposit[2])) {
                    if (course.getAssessMeth().equals("考试")) {
                        if (gradingDeposit.length < 5) {
                            judge = 2;
                        } else {

                            judge = 3;
                        }
                    } else {
                        if (course.getAssessMeth().equals("考察")){
                            if (gradingDeposit.length > 4) {
                                judge = 2;
                            } else {
                                judge = 3;
                            }
                        }else{
                            if(gradingDeposit.length != course.getScoNum()+3){
                                judge = 2;
                            }else{
                                judge = 3;
                            }
                        }
                    }
                    break;
                } else {
                    judge = 1;
                }
            }
        }
        return judge;
    }
    public int ifExistClass(String classorder, ArrayList<Class> classes) {
        int judge = -1;
        for (int i = 0; i < classes.size(); i++) {
            if (classes.get(i).getOrder().equals(classorder)) {
                judge = i;
            }
        }
        return judge;
    }
    public int ifExistStudent(String id, ArrayList<Student> students) {
        int judge = -1;
        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getId().equals(id)) {
                judge = i;
            }
        }
        return judge;
    }
}
class Class {//班级类
    private ArrayList<Student> students = new ArrayList<>();
    private String Order;
    private double score = -1;
    public Class() {
    }
    public double getScore() {
        return score;
    }
    public void setScore(double score) {
        this.score = score;
    }
    public String getOrder() {
        return Order;
    }
    public void setOrder(String Order) {
        this.Order = Order;
    }
    public ArrayList<Student> getStudents() {
        return students;
    }
}
class ClassScore {//班级成绩类
    private AssessmentScores aScore = new AssessmentScores();//考察分数
    private ExamScores emScore = new ExamScores();//考试分数
    private Experiment epScore = new Experiment();//实验分数

    public ClassScore() {
    }
    public AssessmentScores getaScore() {
        return aScore;
    }
    public ExamScores getEmScore() {
        return emScore;
    }
    public Experiment getEpScore() {
        return epScore;
    }
    public void setEpScore(Experiment epScore) {
        this.epScore = epScore;
    }
    public boolean ifaScore(){//判断是否有考察分数
        boolean judge = false;
        if(aScore.getFGrade().getScore() != -1){
            judge = true;
        }
        return judge;
    }
    public boolean ifemScore(){//判断是否有考试分数
        boolean judge = false;
        if(emScore.getRGrade().getScore() != -1){
            judge = true;
        }
        return judge;
    }
}
class Course {//课程类
    private String name;
    private String Type;
    private int ScoNum = 0;
    private String assessMeth;
    public Course() {
    }
    public int getScoNum() {
        return ScoNum;
    }
    public void setScoNum(int scoNum) {
        ScoNum = scoNum;
    }
    public String getname() {
        return name;
    }
    public void setname(String name) {
        this.name = name;
    }
    public void setType(String Type) {
        this.Type = Type;
    }
    public String getAssessMeth() {
        return assessMeth;
    }
    public void setAssessMeth(String assessMeth) {
        this.assessMeth = assessMeth;
    }
}
class CourseSelection {//选课类
    private Student student;
    private ClassScore score;
    private Course course;
    public CourseSelection(Student student,ClassScore score,Course course) {
        this.student = student;
        this.course = course;
        this.score = score;
    }
    public Student getStudent() {
        return student;
    }
    public ClassScore getScore() {
        return score;
    }
    public Course getCourse() {
        return course;
    }
    public CourseSelection() {
    }
    public void setStudent(Student student) {
        this.student = student;
    }
    public void setScore(ClassScore score) {
        this.score = score;
    }
    public void setCourse(Course course) {
        this.course = course;
    }
}
class ExamScores{//考试成绩类
    private Score rGrade = new Score();
    private Score fGrade = new Score();
    public ExamScores() {
    }
    public Score getRGrade() {
        return rGrade;
    }
    public void setRGrade(int rGrade) {
        this.rGrade.setScore(rGrade);
    }
    public Score getFGrade() {
        return fGrade;
    }
    public void setFGrade(int fGrade) {
        this.fGrade.setScore(fGrade);
    }
    public int getRScore(){//总成绩
        int sum = -1;
        if(ifExistCourseScore()){
            if(rGrade.getScore() != -1){
                sum = 0;
                sum = (int)(rGrade.getWeight()*rGrade.getScore()+fGrade.getWeight()*fGrade.getScore());
            }
        }
        return sum;
    }
    public boolean ifExistCourseScore(){
        return rGrade.getScore() != -1 || fGrade.getScore() != -1;
    }
}
class Experiment{//实验成绩类
    private int num;
    private ArrayList<Score> scores = new ArrayList<>();
    public Experiment() {
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public ArrayList<Score> getScores() {
        return scores;
    }
    public void setScores(ArrayList<Score> scores) {
        this.scores = scores;
    }
    public int getRScore(){//总成绩
        double result = -1;
        for(int i = 0;i<scores.size();i++){
            if(i == 0&&scores.get(0).getScore() != -1){
                result = 0;
            }
            if(result != -1)
                result += 1.0*scores.get(i).getScore()*scores.get(i).getWeight();
        }
        return (int)result;
    }
}
class Score {//成绩类
   private int score = -1;
   private double weight = 1;
    public Score() {
    }
    public Score(int score, double weight) {
        this.score = score;
        this.weight = weight;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
    public double getWeight() {
        return weight;
    }
    public void setWeight(double weight) {
        this.weight = weight;
    }
}
class Student {//学生类
    private String id;
    private String name;
    public Student() {
    }
  public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public String getName() {
        return name;
    }
  public void setName(String name) {
        this.name = name;
    }   
}

1)设计与分析

  根据题目要求这次将成绩的继承关系改为了组合关系,具体是将Score类变为实体类,在Experiment类和AssessmentScores类以及ExamScores类中把原来int类型的成绩改为Score类的对象,创建了一个新类叫ClassScore,拥有Experiment类和AssessmentScores类以及ExamScores类的对象作为属性,还有对应的get、set方法、判断是否有考察分数的方法、判断是否有考试分数的方法,用于将三者组合在一起,CourseSelection类中原有的Score类也替换成了ClassScore类,这样就能在总体上保持原有结构。也根据题目要求在Score类里增加了权重的属性,改变了上一次迭代的题目的Check类中的正则表达式,使其可以适用这种情况,改变了Experiment类和AssessmentScores类以及ExamScores类中成绩的计算方式,改为了权重计算。在Main类的主方法中增加了ClassScore类的对象数组用于储存对应数据,去除之前因为继承关系而有的程序,改为同一存储在ClassScore类的对象数组中,并增加设置权重的程序。Main类的输出方法中去除了按拼音排序的语句,改为按字符顺序排序。

 

复杂度:

 

类图:

 

2)遇到的问题与心得

 i.班级平均分过百,因为算班级平均分的中间变量没有重置,在算完一个班级的平均分后归0重置,即可解决问题。

 心得:对于程序中使用的变量应当明确其作用时间和范围,注意其值的重置和变化。

 

 

ii.课程输出结果没按字符顺序排序,因为没有更改比较器,将比较器更改,去除拼音排序的语句即可。

 心得:要多多审视题目,注意题目在迭代中是否更改原有条件。

 

 

3)改进建议

 可进一步将代码提取整合,形成多个方法,减少代码重复和冗杂,也能实现单一职责原则。

三.学习总结与课程评价

 1)第三阶段学习的总结

  对于第三阶段的学习,我确实是学到了很多,通过不断迭代的题目,学会了把问题由浅到深去剖析、去分解,也学会了如何处理多个类之间的关系,对于复制程序的把握能力有了明显提升。在基础知识这一块也有了更深的了解,学会了Set和Map等其它Java类的基本使用,做到会用、能用。在字符串数据处理上也更加熟练,学会了多层次分割、字符串替换、查找、提取。这个阶段也学会了JavaFX的基本使用,能够自己独立地做一个小的图形界面(包括简单动画)。现在就是对于多情况多类型数据处理还尚有欠缺,想的不够全面,还有多情况分类处理和输出不够熟练,容易顾此失彼,以后会继续保持初心,多加练习。对教师、课程、作业、实验、课上及课下组织方式等方面并无什么意见。

 2)课程评价

  对于本课程的教学理念、教学方法、教学组织、教学过程及教学模式我还是很肯定的,这样也确实起到了好的教学效果。不过,也有些我个人感觉美中不足的,首先是PTA的题目,感觉问题的描述有时候会有点不清晰,有点模棱两可,而在多种数据形式同时出现的时候,对于何种输出结果会漏一些情况,导致那些情况没有给一个较准确的输出标准,还有就是在题目中所考察的Java知识点涉及的有些不够广。然后是对于作业的布置时间,我们这边的因素应该是考虑的少了一点,有时候会让我们忙上加忙,时间变得很紧张。

 以上就是我对于第七至十 一次题目集以及第三阶段学习的分析与总结,谢谢观看!

 

标签:空格,Java,String,get,int,学习,judge,至十,public
From: https://www.cnblogs.com/JH2213/p/17500491.html

相关文章

  • Java ssh 访问windows/Linux
    工作中遇到的问题:Javacode运行在一台机器上,需要远程到linux的机器同时执行多种命令。原来采用的方法是直接调用ssh命令或者调用plink的命令。google下java的其他ssh方法,发现有个包。具体介绍如下:GanymedSSH2forJavaisalibrarywhichimplementstheSSH-2protocolinpure......
  • Java中WebService实例
    WebServices是由企业发布的完成其特定商务需求的在线应用服务,其他公司或应用软件能够通过Internet来访问并使用这项在线服务。WebService的关键技术和规则:1.XML:描述数据的标准方法.2.SOAP:表示信息交换的协议(简单对象访问协议).3.WSDL:Web服务描述语言.4.UDDI:通用描述、发现与集......
  • Java并发(十二)----线程应用之多线程解决烧水泡茶问题
    1、背景统筹方法,是一种安排工作进程的数学方法。它的实用范围极广泛,在企业管理和基本建设中,以及关系复杂的科研项目的组织与管理中,都可以应用。怎样应用呢?主要是把工序安排好。比如,想泡壶茶喝。当时的情况是:开水没有;水壶要洗,茶壶、茶杯要洗;火已生了,茶叶也有了。怎么办?办法甲......
  • 阿里的Java开发规范插件验证
    阿里最近有点“烦”,但是作为技术人,更多关注的还是技术层面,其他的就交给有关机构和时间来证明。最近有项工作借鉴了阿里的Java开发规范,为了能让其落地,需要验证方案,而这个Java开发规范提供了对应的验证插件,因此从使用层面,了解一下。目前该插件实现了开发手册中的的53条规则,大部分基于......
  • 对第三阶段PTA集训及Java课程的分析与反思
    前言:本阶段PTA集训共有8-11题目集,涵盖了很多知识点,尤其是成绩计算系列题目,几乎包含了Java目前所学的所有内容,写下来非常不容易(可能对于我这种小菜鸡来说很难)。涵盖的知识点包括对Stirng类型的处理,对象数组的创建与处理,抽象类的使用,异常的处理,逻辑的训练,设计模式的实操。题量不大......
  • java-集合类学习
    LinkedHashMapAspecialconstructorisprovidedtocreatealinkedhashmapwhoseorderofiterationistheorderinwhichitsentrieswerelastaccessed,fromleast-recentlyaccessedtomost-recently(access-order).Thiskindofmapiswell-suitedtobu......
  • linux命令学习-目录大小du
    du命令:显示目录包含的文件大小du可以让我们知道文件和目录所占的空间大小du命令会深入遍历每个目录的子目录,统计所有文件的大小是英语diskusage的缩写,表示“磁盘使用/占用”-h以Ko,Mo,Go的形式显示文件大小-a会显示目录和文件的大小-s只显示当前目录的总大小......
  • 「学习笔记」基环树
    众所周知,一棵有\(n\)个节点的树有\(n-1\)条边,树上没有环。据此,明显的,对于一个有\(n\)个结点\(n\)条边的无向连通图,必定是在一棵树上的任意两个节点之间连一条边构成的。我们把\(n\)个节点\(n\)条边的无向连通图,就称为基环树。基环树上存在环,因此基环树它不是树,而......
  • JAVA判断是否是IDEA里启动
      /***判断是否是idea里面启动*@returntrue:是false:否*/privatestaticbooleancheckRunInIDEA(){try{Class.forName("com.intellij.rt.execution.application.AppMainV2");returntrue;}cat......
  • java8多线程使用示例
    使用CompletableFuture.allOf实现异步执行同步搜集结果/***@authorwjq*@create2022-03-1216:19*/publicclassTestCompleteFuture{privatestaticfinalintcorePoolSize=10;//核心线程数privatestaticfinalint......