OOP第四次到第六次作业总结

OOP第四次到第六次作业总结

前言:

第四次到第六次oop训练集的题目量不多,前三次题量总计25题,难度相比前三次有了大幅提升。
第四次OOP训练集:
第四次训练集主要针对的是对数据的检验与操作。以及面向对象编程的封装性。最后还有一个日期类的题目,为后面日期类的题目做铺垫。
第五次OOP训练集:
第五次训练集主要是对正则表达式的熟练和运用。还有就是类之间关系的实践。例如聚合。
第六次OOP训练集:
第六次训练集

第一次OOP训练:

7-1 菜单计价程序-3

设计与分析:

设计
菜单计价程序设计:
菜品类:对应菜谱上的一道菜的信息,提供的所有菜的信息。例如单价,菜品名称。
菜单类:保存所有菜品信息
订单类:保存用户点的所有菜的信息。并对其总价进行计算。
特殊要求:
代点菜信息包含:桌号 序号 菜品名称 份额 分数。
代点菜是当前桌为另外一桌点菜,信息中的桌号是另一桌的桌号,带点菜的价格计算在当前这一桌。
程序最后按输入的先后顺序依次输出每一桌的总价(注意:由于有代点菜的功能,总价不一定等于当前桌上的菜的价格之和)。
每桌的总价等于那一桌所有菜的价格之和乘以折扣。如存在小数,按四舍五入规则计算,保留整数。
折扣的计算方法(注:以下时间段均按闭区间计算):
周一至周五营业时间与折扣:晚上(17:00-20:30)8折,周一至周五中午(10:30--14:30)6折,其余时间不营业。
周末全价,营业时间:9:30-21:30
如果下单时间不在营业范围内,输出"table " + t.tableNum + " out of opening hours"

分析
这题的细节很多,所以难度偏大,在对用户普通点菜的需求下,还需要满足代点菜的特殊要求。并且还有时间段的限制与折扣。这些都是注重细节的点。而且要写好这题需要正确的辨别各种类之间的关系。如订单类与菜单类之间的联系。还有各个类之间的“交流。

具体代码

import java.util.*;
public class Main {
   public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Judge judge=new Judge();
        Menu menu=new Menu();
        ArrayList<Discount> discounts=new ArrayList<>();
        ArrayList<Table> tables=new ArrayList<>();
        int tableNumber=0;
        ArrayList<Order> orders=new ArrayList<>();
        while (in.hasNext()){
            String str=new String(in.nextLine());
            if(str.equals("end")){//判断结束
                break;
            }
            String[] strSplit=str.split(" ");
            if(judge.isMenu(strSplit.length,strSplit[1])){//入菜单  
menu.addDish(strSplit[0],Integer.parseInt(strSplit[1]));
            }
            if(judge.isTable(strSplit)){//输入桌子序号,时间
                Discount discount=new Discount();
                Order order=new Order();                
                order.setTableNumber(Integer.parseInt(strSplit[1]));
                discount.setTime(strSplit[2],strSplit[3]);
                discounts.add(discount);
                orders.add(order);
                tableNumber++;
            }
            if(judge.isRecord(strSplit)){//输入订单
                int orderNum=Integer.parseInt(strSplit[0]);
                String dishName=strSplit[1];
                int portion=Integer.parseInt(strSplit[2]);
                int num=Integer.parseInt(strSplit[3]);
                orders.get(tableNumber-1).addARecord(orderNum,dishName,portion,num);
                orders.get(tableNumber-1).findRecordByNum(orderNum-1).setDish(menu);
            }
            if(judge.isDelete(strSplit.length,strSplit[1])){                //table.setDeleteNumber(Integer.parseInt(strSplit[0]));
                orders.get(tableNumber-1).setDeleteNumber(Integer.parseInt(strSplit[0]));
            }
        }
        //输出
        for(int i=0;i<orders.size();i++){
            System.out.println("table "+orders.get(i).getTableNumber()+": ");
            for(int j=0;j<orders.get(i).getRecordNumber();j++){
                System.out.println(j+1+" "+orders.get(i).findRecordByNum(j).getDish().getName()+" "+orders.get(i).findRecordByNum(j).getPrice());
            }
            Table table=new Table();        if(orders.get(i).hasDelete(orders.get(i).getDeleteNumber())){
                orders.get(tableNumber-1).delARecordByOrderNum(orders.get(i).getDeleteNumber());
            }
            table.setTototalPrice((int)(orders.get(i).getTotalPrice()*judge.judgeTimeDiscount(discounts.get(i))+0.5));
            tables.add(table);
        }
        for(int i=0;i<tables.size();i++){
            System.out.println("table"+" "+(i+1)+":"+" "+tables.get(i).getTototalPrice());
        }
    }
}
class Discount{
    int year;
    int month;
    int day;
    int hour;
    int minute;
    int second;
    Discount(){}
    void setTime(String timeDay,String timeHour){
        String[] timeDaySplit = timeDay.split("/");
        String[] timeHourSplit =timeHour.split("/");
        this.year=Integer.parseInt(timeDaySplit[0]);
        this.month=Integer.parseInt(timeDaySplit[1]);
        this.day=Integer.parseInt(timeDaySplit[2]);
        this.hour=Integer.parseInt(timeHourSplit[0]);
        this.minute=Integer.parseInt(timeHourSplit[1]);
        this.second=Integer.parseInt(timeHourSplit[2]);
    }
    public int getDay() {
        return day;
    }
    public int getHour() {
        return hour;
    }
    public int getMinute() {
        return minute;
    }
    public int getMonth() {
        return month;
    }
    public int getSecond() {
        return second;
    }
    public int getYear() {
        return year;
    }
}
class Judge{
    Judge(){}
    boolean isMenu(int length,String string){
        if(length==2&&!string.equals("delete")){
            return true;
        }
        else{
            return false;
        }
    }
    boolean isRecord(String[] strSplit){
        if(strSplit.length==4&&!strSplit[0].equals("table")){
            return true;
        }
        else{
            return false;
        }
    }
    boolean isTable(String[] strSplit){
        if(strSplit[0].equals("table")){
            return true;
        }
        else{
            return false;
        }
    }
    boolean isDelete(int length,String string){
        if(length==2&&string.equals("delete")){
            return true;
        }
        else{
            return false;
        }
    }
    double judgeTimeDiscount(Discount discount){
        if(discount.getHour()>=17&&discount.getHour()<20||(discount.getHour()==20&&discount.getMinute()<20)){
            return 0.8;
        }
        else if((discount.getHour()==10&&discount.getMinute()>=30)||discount.getHour()>11&&discount.getHour()<14||(discount.getHour()==14&&discount.getMinute()<30)){
            return 0.6;
        }
        return 1;
    }
}
class Dish{
    String name;//菜品名称
    int unit_price; //单价
    Dish(){}
    Dish(String name,int unit_price){
        this.name=name;
        this.unit_price=unit_price;
    }
    void setName(String name){
        this.name=name;
    }
    void setUnit_price(int unit_price){
        this.unit_price=unit_price;
    }
    String getName(){
        return this.name;
    }
    int getUnit_price(){
        return this.unit_price;
    }
    int getPrice(int portion){//计算菜品价格
        if(portion==1){
            return (int)unit_price;
        }
        else if(portion==2){
            return (int)(unit_price*1.5+0.5);
        }
        else if(portion==3){
            return (int)unit_price*2;
        }
        return 1;
    }
}
class Menu{
    ArrayList<Dish> dishs=new ArrayList<>();//菜品数组,保存所有菜品信息
    Dish searthDish(String dishName){//根据菜名在菜谱中查找菜品信息,返回Dish对象。
        for(int i=0;i<dishs.size();i++){
            if(dishs.get(i).getName().equals(dishName)){
                return dishs.get(i);
            }
        }
        return dishs.get(1);
    }
    void addDish(String dishName,int unit_price){//添加一道菜品信息
        Dish dish=new Dish(dishName,unit_price);
        dishs.add(dish);
    }
}
class Record{
    int orderNum;//序号
    Dish d=new Dish();//菜品
    int portion;//份额(1/2/3代表小/中/大份)
    int numberOfDish;
    String dishName;
    Record(int orderNum,String dishName,int portion,int num){
        this.orderNum=orderNum;
        this.dishName=dishName;
        this.portion=portion;
        this.numberOfDish=num;
    }
    void setDish(Menu menu){//存入订单中
        this.d=menu.searthDish(this.dishName);
    }
    int getOrderNum(){
        return this.orderNum;
    }
    Dish getDish(){
        return this.d;
    }
    int getPortion(){
        return this.portion;
    }
    int getNumberDish(){
        return this.numberOfDish;
    }
    void setOrderNum(int orderNum){
        this.orderNum=orderNum;
    }
    void setDish(Dish dish){
        this.d=dish;
    }
    void setPortion(int portion){
        this.portion=portion;
    }
    void setNumberDish(int numberOfDish){
        this.numberOfDish=numberOfDish;
    }
    int getPrice(){//计价,计算本条记录的价格
        return (int)numberOfDish*d.getPrice(portion);
    }
}
class Order{
    //Record\[\] records;
    int tableNumber;
    int deleteNumber=0;
    ArrayList<Record> records=new ArrayList<>();//保存订单上每一道的记录
    int getTotalPrice(){//计算订单的总价
        int totalPrice=0;
        for(int i=0;i<records.size();i++){
            totalPrice+=records.get(i).getPrice();
        }
        return totalPrice;
    }
    void setTableNumber(int tableNumber){
        this.tableNumber=tableNumber;
    }
    int getTableNumber(){
        return tableNumber;
    }
    void addARecord(int orderNum,String dishName,int portion,int num){//添加一条菜品信息到订单中。
        Record record=new Record(orderNum,dishName,portion,num);
        records.add(record);
    }
    void delARecordByOrderNum(int orderNum){//根据序号删除一条记录
        records.remove(orderNum-1);
    }
    Record findRecordByNum(int orderNum){//根据序号查找一条记录
        return records.get(orderNum);
    }
    int getRecordNumber(){
        return records.size();
    }
    void setDeleteNumber(int deleteNumber){
        this.deleteNumber=deleteNumber;
    }
    public int getDeleteNumber() {
        return deleteNumber;
    }
    boolean hasDelete(int deleteNumber){
        if(deleteNumber==0){
            return false;
        }
        if(deleteNumber>0&&deleteNumber<records.size()){
            return true;
        }
        else{
            return false;
        }
    }
}
class Table{
    int tototalPrice;
    void setTototalPrice(int tototalPrice){
        this.tototalPrice=tototalPrice;
    }
    int getTototalPrice(){
        return this.tototalPrice;
    }
}

踩坑心得

这题菜单的单条数据的处理不难,难得是多条数据的处理,以及每条数据的不同操作。因此这题细节很多,不仅要注意时间是否休息,打折,还要注意是否给他桌买单,所以这题要在总体框架正确的情况下,要注意这些细节才能得到一个比较高的分。

改进建议

先做好设计规划,这题没有得高分很大一部分是因为没有做类图设计

第二次OOP训练集:

7-7 判断两个日期的先后,计算间隔天数、周数

设计与分析:

设计

具体代码

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String firstDate=in.nextLine();
        String secondDate=in.nextLine();
        String[] firstDates=firstDate.split("\\-");
        String[] secondDates=secondDate.split("\\-");
        DateUtil dateFirst = new DateUtil(firstDates);
        DateUtil dateSecond = new DateUtil(secondDates);
        if(dateFirst.compareDates(dateSecond)){
            System.out.println("第一个日期比第二个日期更晚");
        }
        else{
            System.out.println("第一个日期比第二个日期更早");
        }
        System.out.println("两个日期间隔"+dateFirst.getDaysofDates(dateSecond)+"天");
        System.out.println("两个日期间隔"+dateFirst.dayTransformWeek(dateFirst.getDaysofDates(dateSecond))+"周");
}
static class DateUtil{
    private int year=0;
    private int month=0;
    private int day=0;
    public int mon_maxnum[]=new int[]{31,31,28,31,30,31,30,31,31,30,31,30,31};
    
    public DateUtil(){
        
    }
    public DateUtil(int year,int month,int day){
        this.year=year;
        this.month=month;
        this.day=day;
    }
    public DateUtil(String[] date){
        this.year=Integer.parseInt(date[0]);
        this.month=Integer.parseInt(date[1]);
        this.day=Integer.parseInt(date[2]);
    }
    public int getYear(){
        return this.year;
    }
    public void setYear(int year){
        this.year=year;
    }
    public int getMonth(){
        return this.month;
    }
    public void setMonth(int month){
        this.month=month;
    }
    public int getDay(){
        return this.day;
    }
    public void setDay(int day){
        this.day=day;
    }
    public boolean checkInputValidity(){//检测输入的年、月、日是否合法
        if(this.year>0){
            if(isLeapYear(year)){
                setFebruaryMaxDay(this.month);
            }
            if(this.month>=1&&this.month<=12){
                if(this.day>=1&&this.day<=mon_maxnum[this.month]){
                    return true;
                }
                else{
                    return false;
                }
            }
            else{
                return false;
            }
        }
        else{
            return false;
        }
    }
    public boolean isLeapYear(int year){//判断year是否为闰年
        if((year%4==0&&year%100!=0)||year%400==0){
            return true;
        }
        else{
            return false;
        }
    }
    public boolean compareDates(DateUtil date){//比较当前日期与date的大小(先后)//先大为真
        if(this.year>date.year){
            return true;
        }
        else if(this.year==date.year){
            if(this.month>date.month){
                return true;
            }
            else if(this.month==date.month){
                if(this.day>=date.day){
                    return true;
                }
                return false;
            }
            return false;
        }
        return false;
    }
    public boolean equalTwoDates(DateUtil date){//判断两个日期是否相等
        if(this.year==date.year&&this.month==date.month&&this.day==date.day){
            return true;
        }
        return false;
    }
    public int compareDate(DateUtil date){//前一日期更早,则返回-1;更晚则返回1;
        if(this.year<date.year){
            return -1;
        }
        else if(this.year==date.year){
            if(this.month<date.month){
                return -1;
            }
            else if(this.month==date.month){
                if(this.day<date.day){
                    return -1;
                }
                else{
                    return 1;
                }
            }
            else{
                return 1;
            }
        }
        else{
            return 1;
        }
    }
    public int getDaysofDates(DateUtil date){//求当前日期与date之间相差的天数
        int differDay=0;
        int biggerYear;
        int biggerMonth;
        int biggerDay;
        int smallerYear;
        int smallerMonth;
        int smallerDay;
        if(equalTwoDates(date)){
            return 0;
        }
        if(compareDates( date)){
            biggerYear=this.year;
            biggerMonth=this.month;
            biggerDay=this.day;
            smallerYear=date.year;
            smallerMonth=date.month;
            smallerDay=date.day;
        }
        else{
            biggerYear=date.year;
            biggerMonth=date.month;
            biggerDay=date.day;
            smallerYear=this.year;
            smallerMonth=this.month;
            smallerDay=this.day;
        }
            while(biggerYear>smallerYear){
                if(isLeapYear(smallerYear)){
                    differDay+=366;
                    }
                else{
                    differDay+=365;
                }
                    smallerYear+=1;
            }
            while(biggerMonth>smallerMonth){
                if(isLeapYear(smallerYear)){
                    mon_maxnum[2]=29;
                }
                else{
                    mon_maxnum[2]=28;
                }
                differDay+=mon_maxnum[smallerMonth];
                smallerMonth+=1;
            }
            while(biggerMonth<smallerMonth){
                if(isLeapYear(smallerYear)){
                    mon_maxnum[2]=29;
                }
                else{
                    mon_maxnum[2]=28;
                }
                differDay+=mon_maxnum[biggerMonth];
                biggerMonth+=1;
            }
            differDay=differDay+(biggerDay-smallerDay);
            return differDay;
    }
    public void setFebruaryMaxDay(int month){
        this.mon_maxnum[2]=29;
    }
    public int dayTransformWeek(int day){
        return day/7;
    }
}
}

踩坑心得

在这一题的难度来说是简单的,而易错的点就是要注意闰年和该月份的最大天数以及下一天,这些细节注意到的话,这题很简单。

改进建议

这题的改进可以将此写为一个类,并且尽量遵循单一职责原则,有些方法的职责太重了。使用Java 8的时间API处理日期和时间,这将使代码更加简洁易读。可以使用LocalDate类表示日期。另一个就是使用异常处理来捕捉任何可能的错误,例如输入格式不正确或者日期范围超出了可处理的范围。

第五次OOP训练集:

7-1 正则表达式训练-QQ号校验

设计与分析:

Java中使用正则表达式需要用到Pattern和Matcher两个类。Pattern类表示一个正则表达式的编译结果,而Matcher类则是对输入字符串进行匹配的操作类。
而最后则是要熟悉正则表达式的基础语法与用法。简洁高效的处理匹配,替换,查找的功能。这一题主要是匹配功能。
分析
这题主要运用正则表达式来解决问题,熟练运用表达式,学习语法。

具体代码

 import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String QQNumber=in.nextLine();
        String regex="[1-9][0-9]{4,14}";
        boolean isQQNumberLegal=QQNumber.matches(regex);//正则表达式的匹配
        if(isQQNumberLegal){
            System.out.println("你输入的QQ号验证成功");
        }
        else{
            System.out.println("你输入的QQ号验证失败");
        }
    }
}

踩坑心得

这是第一次学习使用正则表达式来解决问题,所以在一些语法上面有些问题,例如【0-9】写成了【0,9】,这里卡了一点时间,最后也是很顺利的改回来了。

改进建议

改进的话就是题目简单,在格式上改进的更加规范,易读,简洁。

7-5 日期问题面向对象设计(聚合一)

设计与分析:

类图:

分析
首先对聚合这个定义进行分析:聚合是一种关系,在聚合关系中,一个对象包含了对另一个对象的引用或多个对象的引用,这些被引用的对象在解除聚合关系时,仍然可以继续存在。因此聚合关系是一种弱关联关系。
而在老师给的类图中,DataUtil类聚合了Day类,Day类聚合了Month类,Month类聚合了Year类。在实现各个类中的方法时,也要注意各类之间的联系与交流。

具体代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int year = 0;
        int month = 0;
        int day = 0;
        int choice = in.nextInt();
        if (choice == 1) { // test getNextNDays method
            int m = 0;
            year = Integer.parseInt(in.next());
            month = Integer.parseInt(in.next());
            day = Integer.parseInt(in.next());
            m = in.nextInt();
            DateUtil date = new DateUtil(day, month, year);
            if (!date.checkInputValidity()) {
                System.out.println("Wrong Format");
                System.exit(0);
            }

            System.out.println(date.getNextNDay(m).showDate());


        }
        else if (choice == 2) { // test getPreviousNDays method
            int n = 0;

            year = Integer.parseInt(in.next());
            month = Integer.parseInt(in.next());
            day = Integer.parseInt(in.next());
            n = in.nextInt();
            DateUtil date = new DateUtil(day, month, year);
            if (!date.checkInputValidity()) {//检查是否合法
                System.out.println("Wrong Format");
                System.exit(0);
            }

            System.out.println(date.getPreviousNDay(n).showDate());

        }
        else if (choice == 3) { // test getDaysofDates method
            year = Integer.parseInt(in.next());
            month = Integer.parseInt(in.next());
            day = Integer.parseInt(in.next());
            int anotherYear = Integer.parseInt(in.next());
            int anotherMonth = Integer.parseInt(in.next());
            int anotherDay = Integer.parseInt(in.next());
            DateUtil date=new DateUtil(day,month,year);//前一个日期
            DateUtil anotherDate=new DateUtil(anotherDay,anotherMonth,anotherYear);//后一个日期
            if (!date.checkInputValidity()||!anotherDate.checkInputValidity()) {//检查是否合法
                System.out.println("Wrong Format");
                System.exit(0);
            }
            System.out.println(date.getDaysofDates(anotherDate));
        }
        else{//输入别的数据
            System.out.println("Wrong Format");
            System.exit(0);
        }
    }
}
 class DateUtil{
    Day day;
    DateUtil(){}
    DateUtil(int day,int month,int year){//构造函数
        this.day=new Day(year,month,day);
    }
    public Day getDay() {
        return day;
    }
    public void setDay(Day day) {
        this.day = day;
    }
    boolean checkInputValidity(){
        if(day.month.validate()&&day.month.year.validate()&&day.validate()){
            return true;
        }
        return false;
    }
    boolean compareDates(DateUtil date){//比较两个日期的大小,前一个日期晚于后一个日期则返回真,否则,返回假。
        if(this.day.getMonth().getYear().getValue()>date.day.getMonth().getYear().getValue()){//比较年份
            return true;
        }
        else if(this.day.getMonth().getYear().getValue()<date.day.getMonth().getYear().getValue()){
            return false;
        }
        else{//如果年份相等
            if(this.day.getMonth().getValue()>date.day.getMonth().getValue()){//比较月份
                return true;
            }
            else if(this.day.getMonth().getValue()>date.day.getMonth().getValue()){
                return false;
            }
            else{
                if(this.day.getValue()>date.day.getValue()){
                    return true;
                }
                else{
                    return false;
                }
            }
        }
    }//比较两个日期的大小,前一个日期晚于后一个日期则返回真,否则,返回假。
    boolean equalTwoDates(DateUtil date){//两个日期相等
        if(this.day.getValue()==date.day.getValue()&&this.day.getMonth().getValue()==date.day.getMonth().getValue()&&this.day.getMonth().getYear().getValue()==date.day.getMonth().getYear().getValue()){
            return true;
        }//比较两个日期的天数,月份,年份是否相等
        return false;
    }//两个日期相等
    String showDate(){
        StringBuffer data=new StringBuffer();
        data.append(day.getMonth().getYear().getValue());//年份
        data.append("-");
        data.append(day.getMonth().getValue());//月份
        data.append("-");
        data.append(day.getValue());//天数
        return data.toString();
    }//按照格式输出时间year-month-day
    DateUtil getNextNDay(int n){
        DateUtil date = new DateUtil(this.day.getValue(),this.day.getMonth().getValue(),this.day.getMonth().getYear().getValue());
        while (n!=0){
            n--;
            date.day.dayIncrement();
        }
        return date;
    }//得到下n天的日期
    DateUtil getPreviousNDay(int n){
        DateUtil date = new DateUtil(this.day.getValue(),this.day.getMonth().getValue(),this.day.getMonth().getYear().getValue());
        while (n!=0){
            n--;
            date.day.dayReduction();
        }
        return date;
    }//得到上n天的日期
    int getDaysofDates(DateUtil date){
        DateUtil thisDate=new DateUtil(this.day.getValue(),this.day.getMonth().getValue(),this.day.getMonth().getYear().getValue());
        int number=0;
        if(equalTwoDates(date)){
            return 0;
        }
        if(thisDate.compareDates(date)){
            while(!thisDate.equalTwoDates(date)){//比较两个日期是否相等
                date.day.dayIncrement();
                number++;
            }
            return number;
        }
        else{
            while (!thisDate.equalTwoDates(date)){//比较两个日期是否相等
                thisDate.day.dayIncrement();
                number++;
            }
            return number;
        }
    }
}
class Day{
    int value;
    Month month;
    int[] mon_maxnum={31,28,31,30,31,30,31,31,30,31,30,31};
    Day(){

    }
    Day(int yearValue,int monthValue,int dayValue){
        this.month=new Month(yearValue,monthValue);
        this.value=dayValue;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
    public Month getMonth() {
        return month;
    }
    public void setMonth(Month value) {
        this.month = value;
    }
    void resetMin(){
        value=1;
    }//将日期复位为1
    void resetMax(){
        if(month.getYear().isLeapYear()){//是否为闰年
            mon_maxnum[1]=29;//闰年将二月改为29天
        }
        else{
            mon_maxnum[1]=28;
        }
        value=mon_maxnum[month.getValue()-1];//将日期改为月份最大值

    }//将日期改为月份最大值
    boolean validate(){
        if(month.getYear().isLeapYear()){
            mon_maxnum[1]=29;
        }
        else{
            mon_maxnum[1]=28;
        }
        if(value>=1&&value<=mon_maxnum[month.getValue()-1]){
            return true;
        }
        return false;
    }//验证天数合法性
    void dayIncrement(){
        value++;
        if(month.getYear().isLeapYear()){
            mon_maxnum[1]=29;
        }
        else{
            mon_maxnum[1]=28;
        }
        if(value>mon_maxnum[getMonth().getValue()-1]){
            resetMin();
            month.monthIncrement();
        }
    }//日增量
    void dayReduction(){
        value--;
        if(value==0){
            month.monthReduction();
            resetMax();



        }
    }//日减量

}
class Month{
    int value;
    Year year;
    Month(){

    }
    Month(int yearValue,int monthValue){
        this.year=new Year(yearValue);
        this.value=monthValue;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Year getYear() {
        return year;
    }

    public void setYear(Year year) {
        this.year = year;
    }
    void resetMin(){
        this.value=1;
    }
    void resetMax(){
        this.value=12;
    }
    boolean validate(){
        if(value>=1&&value<=12){
            return true;
        }
        return false;
    }//验证月份合法性
    void monthIncrement(){
        value++;
        if(value>12){
            resetMin();
            year.yearIncrement();
        }
    }
    void monthReduction(){
        value--;
        if(value==0){
            resetMax();
            year.yearReduction();
        }
    }
}
class Year{
    int value;
    Year(){

    }
    Year(int value){
        this.value=value;
    }

    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    boolean isLeapYear(){
        if(value%400==0||(value%4==0&&value%100!=0)){
            return true;
        }
        return false;
    }//判断是否为闰年
    boolean validate(){
        if(value>=1900&&value<=2050){
            return true;
        }
        return false;
    }//验证年的合法性
    void yearIncrement(){
        value++;
    }
    void yearReduction(){
        value--;
    }

}


踩坑心得:

这题较为简单,与之前的日期类题目一样,注意日期越界,和日期的加减操作。还有就是日期的特殊性,例如一年的最后一天的下一天是下一年的第一天,这类特殊性的情况都要考虑。

改进建议

参考LocalDateTime类中的相关方法,使代码更加简洁。也更适用于更多的不同的时间格式。

日期问题面向对象设计(聚合二)

设计与分析:

类图:

分析
与上一题不同,这一题所给出的类图使是DateUtil类聚合Day类,Month类,Year类。类与类之间的关系不同。可以在上一题的基础上改进代码,使之改变类间关系。

具体代码

 import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int year = 0;
        int month = 0;
        int day = 0;
        int choice = in.nextInt();
        if (choice == 1) { // test getNextNDays method
            int m = 0;
            year = Integer.parseInt(in.next());
            month = Integer.parseInt(in.next());
            day = Integer.parseInt(in.next());
            m = in.nextInt();
            Year year1=new Year(year);
            Month month1=new Month(month);
            Day day1=new Day(day);
            DateUtil date = new DateUtil();
            date.setYear(year1);
            date.setMonth(month1);
            date.setDay(day1);
            if (!date.checkInputValidity()) {
                System.out.println("Wrong Format");
                System.exit(0);
            }
            System.out.print(year+"-"+month+"-"+day+" next "+m+" days is:");
            System.out.print(date.getNextNDay(m).showDate());


        }
        else if (choice == 2) { // test getPreviousNDays method
            int n = 0;
            year = Integer.parseInt(in.next());
            month = Integer.parseInt(in.next());
            day = Integer.parseInt(in.next());
            n = in.nextInt();
            Year year1=new Year(year);
            Month month1=new Month(month);
            Day day1=new Day(day);
            DateUtil date = new DateUtil();
            date.setYear(year1);
            date.setMonth(month1);
            date.setDay(day1);
            if (!date.checkInputValidity()) {//检查是否合法
                System.out.println("Wrong Format");
                System.exit(0);
            }
            System.out.print(year+"-"+month+"-"+day+" previous "+n+" days is:");
            System.out.print(date.getPreviousNDay(n).showDate());

        }
        else if (choice == 3) { // test getDaysofDates method
            year = Integer.parseInt(in.next());
            month = Integer.parseInt(in.next());
            day = Integer.parseInt(in.next());
            int anotherYear = Integer.parseInt(in.next());
            int anotherMonth = Integer.parseInt(in.next());
            int anotherDay = Integer.parseInt(in.next());

            Year year1=new Year(year);
            Month month1=new Month(month);
            Day day1=new Day(day);
            DateUtil date = new DateUtil();
            date.setYear(year1);
            date.setMonth(month1);
            date.setDay(day1);

            Year anotherYear1=new Year(anotherYear);
            Month anotherMonth1=new Month(anotherMonth);
            Day anotherDay1=new Day(anotherDay);
            DateUtil anotherDate = new DateUtil();
            anotherDate.setYear(anotherYear1);
            anotherDate.setMonth(anotherMonth1);
            anotherDate.setDay(anotherDay1);//后一个日期

            if (!date.checkInputValidity()||!anotherDate.checkInputValidity()) {//检查是否合法
                System.out.println("Wrong Format");
                System.exit(0);
            }
            System.out.print("The days between "+year+"-"+month+"-"+day+" and ");
            System.out.print(anotherYear+"-"+anotherMonth+"-"+anotherDay+" are:");
            System.out.print(date.getDaysofDates(anotherDate));
        }
        else{//输入别的数据
            System.out.println("Wrong Format");
            System.exit(0);
        }
    }
}
 class DateUtil{
    Year year;
    Month month;
    Day day;
    int[] mon_maxnum={31,28,31,30,31,30,31,31,30,31,30,31};
    DateUtil(){}
    DateUtil(int year,int month,int day){//构造函数
        this.day=new Day( day);
        this.month=new Month(month);
        this.year=new Year(year);
    }
     public Year getYear() {//获取年份对象
         return year;
     }
     public void setYear(Year year) {//设置年份对象
         this.year = year;
     }
     public Month getMonth() {
         return month;
     }//获取月份对象
     public void setMonth(Month month) {
         this.month = month;
     }//设置月份对象
     public Day getDay() {
        return day;
    }//获取天数对象
     public void setDay(Day day) {
        this.day = day;
    }//设置天数对象
     void setDayMin(){
        this.day.setValue(1);
     }//重置天数为1
     void setDayMax(){
        this.day.setValue(mon_maxnum[month.getValue()-1]);
     }//重置天数为该月份最大值
     boolean checkInputValidity(){
         if(year.isLeapYear()){
             mon_maxnum[1]=29;
         }
         else{
             mon_maxnum[1]=28;
         }
        if(month.validate()&&year.validate()){
            if(day.getValue()>=1&&day.getValue()<=mon_maxnum[month.getValue()-1]) {
                return true;
            }
            else{
                return false;
            }
        }
        return false;
    }//检查数据合法性
     DateUtil getNextNDay(int n){
        DateUtil date = new DateUtil(this.year.getValue(),this.month.getValue(),this.day.getValue());
        while (n!=0){
            n--;
            if(date.year.isLeapYear()){
                date.mon_maxnum[1]=29;
            }
            else{
                date.mon_maxnum[1]=28;
            }
            date.day.dayIncrement();
            if(date.day.getValue()>date.mon_maxnum[date.month.getValue()-1]){
                date.setDayMin();
                date.month.monthIncrement();
            }
            if(date.month.getValue()>12){
                date.month.resetMin();
                date.year.yearIncrement();
            }
        }
        return date;
    }//得到下n天的日期
     DateUtil getPreviousNDay(int n){
        DateUtil date = new DateUtil(this.year.getValue(),this.month.getValue(),this.day.getValue());
        while (n!=0){
            n--;
            if(date.year.isLeapYear()){
                date.mon_maxnum[1]=29;
            }
            else{
                date.mon_maxnum[1]=28;
            }
            date.day.dayReduction();
            if(date.day.getValue()<1){
                date.month.monthReduction();
                if(date.month.getValue()<1){
                    date.month.resetMax();
                    date.year.yearReduction();
                }
                date.setDayMax();
            }
        }
        return date;
    }//得到上n天的日期
     boolean compareDates(DateUtil date){//比较两个日期的大小,前一个日期晚于后一个日期则返回真,否则,返回假。
         if(this.year.getValue()>date.year.getValue()){//比较年份
             return true;
         }
         else if(this.year.getValue()<date.year.getValue()){
             return false;
         }
         else{//如果年份相等
             if(this.month.getValue()>date.month.getValue()){//比较月份
                 return true;
             }
             else if(this.month.getValue()>date.month.getValue()){
                 return false;
             }
             else{
                 if(this.day.getValue()>date.day.getValue()){
                     return true;
                 }
                 else{
                     return false;
                 }
             }
         }
     }//比较两个日期的大小,前一个日期晚于后一个日期则返回真,否则,返回假。
     boolean equalTwoDates(DateUtil date){//两个日期相等
         if(this.day.getValue()==date.day.getValue()&&this.month.getValue()==date.month.getValue()&&this.year.getValue()==date.year.getValue()){
             return true;
         }//比较两个日期的天数,月份,年份是否相等
         return false;
     }//两个日期相等
     int getDaysofDates(DateUtil date){
        DateUtil thisDate=new DateUtil(this.year.getValue(),this.month.getValue(),this.day.getValue());
        int number=0;
        if(equalTwoDates(date)){
            return 0;
        }
        if(thisDate.compareDates(date)){
            while(!thisDate.equalTwoDates(date)){//比较两个日期是否相等
                if(date.year.isLeapYear()){
                    date.mon_maxnum[1]=29;
                }
                else{
                    date.mon_maxnum[1]=28;
                }
                date.day.dayIncrement();
                if(date.day.getValue()>date.mon_maxnum[date.month.getValue()-1]){
                    date.setDayMin();
                    date.month.monthIncrement();
                }
                if(date.month.getValue()>12){
                    date.month.resetMin();
                    date.year.yearIncrement();
                }
                number++;
            }
            return number;
        }
        else{
            while (!thisDate.equalTwoDates(date)){//比较两个日期是否相等
                if(thisDate.year.isLeapYear()){
                    thisDate.mon_maxnum[1]=29;
                }
                else{
                    thisDate.mon_maxnum[1]=28;
                }
                thisDate.day.dayIncrement();
                if(thisDate.day.getValue()>thisDate.mon_maxnum[thisDate.month.getValue()-1]){
                    thisDate.setDayMin();
                    thisDate.month.monthIncrement();
                }
                if(thisDate.month.getValue()>12){
                    thisDate.month.resetMin();
                    thisDate.year.yearIncrement();
                }
                number++;
            }
            return number;
        }
    }//返回两个日期之间的天数
     String showDate(){
         StringBuffer data=new StringBuffer();
         data.append(year.getValue());//年份
         data.append("-");
         data.append(month.getValue());//月份
         data.append("-");
         data.append(day.getValue());//天数
         return data.toString();
     }//按照格式输出时间year-month-day
}
class Day{
    int value;
    Day(){

    }
    Day(int dayValue){
        this.value=dayValue;
    }
    public int getValue() {
        return value;
    }//获取天数
    public void setValue(int value) {
        this.value = value;
    }//设置天数
    void dayIncrement(){
        value++;
    }//日增量
    void dayReduction(){
        value--;
    }//日减量

}
class Month{
    int value;
    Month(){
    }
    Month(int monthValue){
        this.value=monthValue;
    }
    public int getValue() {
        return value;
    }//获取月份
    public void setValue(int value) {
        this.value = value;
    }//设置月份
    void resetMin(){
        this.value=1;
    }//重置月份为1
    void resetMax(){
        this.value=12;
    }//重置月份为12
    boolean validate(){
        if(value>=1&&value<=12){
            return true;
        }
        return false;
    }//验证月份合法性
    void monthIncrement(){
        value++;
    }//月增量
    void monthReduction(){
        value--;
    }//月减量
}
class Year{
    int value;
    Year(){

    }
    Year(int value){
        this.value=value;
    }
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }//设置年份
    boolean isLeapYear(){
        if(value%400==0||(value%4==0&&value%100!=0)){
            return true;
        }
        return false;
    }//判断是否为闰年
    boolean validate(){
        if(value>=1820&&value<=2020){
            return true;
        }
        return false;
    }//验证年的合法性
    void yearIncrement(){
        value++;
    }//年增量
    void yearReduction(){
        value--;
    }//年减量

}

生成报表

踩坑心得

尽量让代码遵循单一职责原则,这样更改代码所出现的错误会跟少。也更易修改。这一题代码并不需要改特别多,只要改类间光系。所以这题重点是让你理解不同关系的实现方法。

改进建议

改进建议是在很多类中都有类似的方法。可以创建接口来规范代码。使程序设计更加简洁、易于维护。

7-3 水文数据校验及处理

设计与分析:

类图:

分析

使用 Java 中的字符串处理类以及正则表达式对输入字符串数据进行分割,合法性校验及计算。

具体代码

import java.time.format.DateTimeFormatter;
import java.util.*;
import java.time.LocalDateTime;
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);
        ArrayList<HydrologicalInfo>hydrologicalInfoArrayList=new ArrayList<>();
        DealDate dealDate=new DealDate();
        boolean allDataValidate=true;
        String data=new String();
        int row=1;
        data=in.nextLine();
        while(!data.equals("exit")){
            if(data.isBlank()||data.isEmpty()){
                break;
            }
            CheckData checkData=new CheckData(data,row);
            if(checkData.validateData()){
                hydrologicalInfoArrayList.add(checkData.toHydrologicalInfo());
            }
            else{
                allDataValidate=false;
                System.out.println("Data:"+data);
            }
            data=in.nextLine();
            row++;
        }
        if(allDataValidate){
            for(int i=0;i<hydrologicalInfoArrayList.size();i++){

                dealDate.computeData(hydrologicalInfoArrayList.get(i));
            }
            dealDate.getDealDataResult();
        }




    }
}
class CheckData{
    String data=new String();//水文信息

    int row;//当前行数
    CheckData(){

    }
    CheckData(String data,int row){
        this.data=data;
        this.row=row;
    }
    public int getRow() {
        return row;
    }
    public String getData() {
        return data;
    }
    public void setData(String data) {
        this.data = data;
    }
    public void setRow(int row) {
        this.row = row;
    }
    boolean validateData(){//数据合法性校验
        String regex="[^\\|]+(\\|[^\\|]+){4}";
        Pattern pattern =Pattern.compile(regex);
        boolean flag=data.matches(regex);
        if(!flag){
            System.out.println("Wrong Format");
            return false;
        }
        String[] dataSplit=data.split("\\|");
        String[] dataTime=dataSplit[0].split("\\/| |:");
        String objectWaterLevel=dataSplit[1];
        String actualWaterLevel=dataSplit[2];
        String objectGateOpening=dataSplit[3].split("\\/")[0];
        String actralGateOpening=dataSplit[3].split("\\/")[1];
        String waterFlow=dataSplit[4];

        if(!validateMeasureDateTime(dataSplit[0])){
            System.out.println("Row:"+row+",Column:1Wrong Format");
        }
        if(!validateWaterLevel(objectWaterLevel)){//第二列
            System.out.println("Row:"+row+",Column:2Wrong Format");
        }
        if(!validateWaterLevel(actualWaterLevel)){//第三列
            System.out.println("Row:"+row+",Column:3Wrong Format");
        }

        if(!validateGateOpening(objectGateOpening)){//第四列
            System.out.println("Row:"+row+",Column:4Wrong Format");
        }
        if(!validateGateOpening(actralGateOpening)){//第五列
            System.out.println("Row:"+row+",Column:5Wrong Format");
        }
        if(!validateWaterFlow(waterFlow)){//第六列
            System.out.println("Row:"+row+",Column:6Wrong Format");
        }

        if(validateMeasureDateTime(dataSplit[0])&&
                validateWaterLevel(objectWaterLevel)&&
                validateWaterLevel(actualWaterLevel)&&
                validateGateOpening(objectGateOpening)&&
                validateGateOpening(actralGateOpening)&&
                validateWaterFlow(waterFlow)
        ){
            return true;
        }
        return false;

    }
    boolean validateMeasureDateTime(String measureDateTime){//采集时间合法性校验
        //年[1,9999]
        String regex="(\\s+)?[1-9][0-9]{0,3}\\/([1-9]|(1[0-2]))\\/(([1-9])|([1-2][0-9])|(30))[ ]([02468]|([1-2][02468])):[0][0]+(\\s+)?";
        Pattern pattern =Pattern.compile(regex);
        boolean flag=measureDateTime.matches(regex);
        String[] dataTime=measureDateTime.split("\\/| |:");
        try{
            LocalDateTime dateTime =LocalDateTime.of(Integer.parseInt(dataTime[0]),Integer.parseInt(dataTime[1]),Integer.parseInt(dataTime[2]),Integer.parseInt(dataTime[3]),Integer.parseInt(dataTime[4]));
        }
        catch (Exception e){
            return false;
        }
        finally {
            return flag;
        }
    }
    boolean validateWaterLevel(String waterLevel){//水位合法性检验
        //取值范围为[1,1000)
        String regex="(\\s+)?[1-9][0-9]{0,3}(\\.?)[0-9]{0,3}(\\s+)?";
        Pattern pattern=Pattern.compile(regex);
        boolean flag=waterLevel.matches(regex);
        return flag;
    }
    boolean validateWaterFlow(String waterFlow) {//流量合法性检验
        String regex="(\\s+)?[1-9][0-9]{0,3}(\\.?)[0-9]{0,3}(\\s+)?";
        Pattern pattern=Pattern.compile(regex);
        boolean flag=waterFlow.matches(regex);
        return flag;
    }
    boolean validateGateOpening(String gateOpening){//开度合法性检验
        String regex="(\\s+)?[1-9]\\.[0-9][0-9](\\s+)?";
        Pattern pattern=Pattern.compile(regex);
        boolean flag=gateOpening.matches(regex);
        return flag;
    }
    HydrologicalInfo toHydrologicalInfo(){

        String[] dataSplit=data.split("\\|");
        String[] dataTime=dataSplit[0].split("\\/| |:");
        LocalDateTime measureDateTime =LocalDateTime.of(Integer.parseInt(dataTime[0]),Integer.parseInt(dataTime[1]),Integer.parseInt(dataTime[2]),Integer.parseInt(dataTime[3]),Integer.parseInt(dataTime[4]));
        String objectWaterLevel=dataSplit[1];
        String actualWaterLevel=dataSplit[2];
        String objectGateOpening=dataSplit[3].split("\\/")[0];
        String actralGateOpening=dataSplit[3].split("\\/")[1];
        String waterFlow=dataSplit[4];
        HydrologicalInfo hydrologicalInfo=new HydrologicalInfo(measureDateTime,Double.parseDouble(objectWaterLevel),Double.parseDouble(actualWaterLevel) ,Double.parseDouble(objectGateOpening),Double.parseDouble(actralGateOpening),Double.parseDouble(waterFlow) );
        hydrologicalInfo.setRow(row);
        return hydrologicalInfo;
    }//转换为对象

}
class HydrologicalInfo{
    LocalDateTime measureDateTime;
    double objectWaterLevel;
    double actualWaterLevel;
    double objectGateOpening;
    double actralGateOpening;
    double waterFlow;
    int row;
    HydrologicalInfo(){}
    HydrologicalInfo(
            LocalDateTime measureDateTime,
            double objectWaterLevel,
            double actualWaterLevel,
            double objectGateOpening,
            double actralGateOpening,
            double waterFlow){
         this.measureDateTime=measureDateTime;
         this.objectWaterLevel=objectWaterLevel;
         this.actualWaterLevel=actualWaterLevel;
         this.objectGateOpening=objectGateOpening;
         this.actralGateOpening=actralGateOpening;
         this.waterFlow=waterFlow;

    }

    public int getRow() {
        return row;
    }
    public void setRow(int row) {
        this.row = row;
    }
    public double getActralGateOpening() {
        return actralGateOpening;
    }
    public double getActualWaterLevel() {
        return actualWaterLevel;
    }
    public double getObjectGateOpening() {
        return objectGateOpening;
    }
    public double getObjectWaterLevel() {
        return objectWaterLevel;
    }
    public double getWaterFlow() {
        return waterFlow;
    }
    public LocalDateTime getMeasureDateTime() {
        return measureDateTime;
    }
    public void setActralGateOpening(double actralGateOpening) {
        this.actralGateOpening = actralGateOpening;
    }
    public void setActualWaterLevel(double actualWaterLevel) {
        this.actualWaterLevel = actualWaterLevel;
    }
    public void setMeasureDateTime(LocalDateTime measureDateTime) {
        this.measureDateTime = measureDateTime;
    }
    public void setObjectWaterLevel(double objectWaterLevel) {
        this.objectWaterLevel = objectWaterLevel;
    }
    public void setObjectGateOpening(double objectGateOpening) {
        this.objectGateOpening = objectGateOpening;
    }
    public void setWaterFlow(double waterFlow) {
        this.waterFlow = waterFlow;
    }
}
class DealDate{
    StringBuilder sb=new StringBuilder();
    double MaxActualWaterLevel=0;
    double totalWaterFlow=0;
    DealDate(){}
    DealDate(StringBuilder sb){

    }
    StringBuilder getSb(){
        return this.sb;
    }
    void setSb(StringBuilder sb){
        this.sb=sb;
    }
    void getDealDataResult(){
        showMaxActualWaterLevel();
        showTotalWaterFlow();
    }
    void showMaxActualWaterLevel(){
        System.out.printf("Max Actual Water Level:"+"%.2f\n",getMaxActualWaterLevel());
    }

    public double getMaxActualWaterLevel() {
        return MaxActualWaterLevel;
    }
    void showTotalWaterFlow(){
        System.out.printf("Total Water Flow:"+"%.2f\n",totalWaterFlow);
    }

    public void setTotalWaterFlow(double totalWaterFlow) {
        this.totalWaterFlow = totalWaterFlow;
    }
    void computeTotalWaterFlow(double waterFlow){
        this.totalWaterFlow+=2*60*60*waterFlow;
    }
    void setMaxActualWaterLevel(double waterLevel){
        if(MaxActualWaterLevel<waterLevel){
            this.MaxActualWaterLevel=waterLevel;
        }
    }

    public double getTotalWaterFlow() {
        return totalWaterFlow;
    }

    void computeData(HydrologicalInfo hydrologicalInfo){

        if(hydrologicalInfo.getActralGateOpening()>hydrologicalInfo.getObjectGateOpening()){
            System.out.println("Row:"+hydrologicalInfo.getRow()+" GateOpening Warning");
        }
        setMaxActualWaterLevel(hydrologicalInfo.getActualWaterLevel());
        computeTotalWaterFlow(hydrologicalInfo.getWaterFlow());


    }


}


踩坑心得


这一题写到最后有点找不出问题所在了。
对单条水文的校验都是对的。不过对多条水文信息的检测。题目所给出的测试用例过了,不过PTA中的测试用例没过,说明程序中还存在问题没有解决。

改进建议

改进最后的多条信息的检测,使用接口简化代码,使代码更加整洁,易读。

7-4 ATM机类结构设计(一)

设计与分析:

类图:

分析
完成用户的存款、取款以及查询余额功能。

具体代码



import java.util.*;
public class Main {
    public static void main(String[]args){
        ChinaUnionPay chinaUnionPay=new ChinaUnionPay();
        Scanner in=new Scanner(System.in);
        String data=in.nextLine();
        while(!data.equals("#")){
            String dataSplit[]=data.split("\\s{1,}");//分割
            ATM atm=new ATM();
            try{
                atm=chinaUnionPay.SearchATM(dataSplit[2]);//搜索ATM
                if(!chinaUnionPay.validCardID(dataSplit[0])){//卡号是否存在
                    System.out.println("Sorry,this card does not exist.");
                    System.exit(0);
                }
                if(chinaUnionPay.isCrossBank(atm,dataSplit[0])){//是否跨行操作
                    System.out.println("Sorry,cross-bank withdrawal is not supported.");
                    System.exit(0);
                }
                atm.businessOperations(dataSplit);//在自家ATM上进行操作
                atm.showOperations(dataSplit);//输出操作
                atm.showBalance(dataSplit);//输出余额
            }
            catch (Exception e){//只有卡号
                chinaUnionPay.showBalance(dataSplit[0]);//输出余额
            }
            finally {

            }

            data=in.nextLine();
        }

    }
}
class User{
    private String UserName;//用户名
    ArrayList<Account>accountArrayList=new ArrayList<>();//账号集合
    User(){
    }
    User(String UserName){
        this.UserName=UserName;
    }
    public void AddAccount(Account account){//添加账户到集合中
        this.accountArrayList.add(account);
    }


    public String getUserName() {
        return UserName;
    }
    public void setUserName(String userName) {
        UserName = userName;
    }

    public void setAccountArrayList(ArrayList<Account> accountArrayList) {
        this.accountArrayList = accountArrayList;
    }

    public ArrayList<Account> getAccountArrayList() {
        return accountArrayList;
    }
}
class Account{
    private String AccountNumber;//银行账号
    private double deposit;//存款
    ArrayList<Card> cardArrayList=new ArrayList<>();
    Account(){

    }

    Account(String AccountNumber,double deposit){
        this.AccountNumber=AccountNumber;
        this.deposit=deposit;
    }

    public double getDeposit() {
        return deposit;
    }

    public void setDeposit(double deposit) {
        this.deposit = deposit;
    }

    public void AddCard(Card card){//添加卡到集合中
        this.cardArrayList.add(card);
    }

    public ArrayList<Card> getCardArrayList() {
        return cardArrayList;
    }

    public String getAccountNumber() {
        return AccountNumber;
    }

    public void setAccountNumber(String accountNumber) {
        AccountNumber = accountNumber;
    }

    public void setCardArrayList(ArrayList<Card> cardArrayList) {
        this.cardArrayList = cardArrayList;
    }
    public void depositMoney(double operations){//存入钱
        this.deposit-=operations;
    }
    public void withdrawMoney(double operations){//取出钱
        if(operations>this.getDeposit()){
            System.out.println("Sorry,your account balance is insufficient.");
            System.exit(0);
        }

        this.deposit-=operations;

    }


}
class Card{
    private String CardId;//卡号
    private String password;//密码
    private Bank bank;//银行
    private String ownerName;//拥有者名字
    Card(){
        super();
    }
    Card(String ownerName,String CardId,String password,Bank bank){
        super();
        this.bank=bank;
        this.password=password;
        this.CardId=CardId;
        this.ownerName=ownerName;
    }

    public void setBank(Bank bank) {
        this.bank = bank;
    }

    public void setCardId(String cardId) {
        CardId = cardId;
    }


    public void setPassword(String password) {
        this.password = password;
    }

    public Bank getBank() {
        return bank;
    }



    public String getCardId() {
        return CardId;
    }

    public String getPassword() {
        return password;
    }


    public void setOwnerName(String ownerName) {
        this.ownerName = ownerName;
    }

    public String getOwnerName() {
        return ownerName;
    }
}
class ATM{
    private String ATMNumber;
    private Bank bank;
    ATM(){
        super();
    }
    ATM(String ATMNumber,Bank bank){
        this.ATMNumber=ATMNumber;
        this.bank=bank;
    }
    public void businessOperations(String[] data){//进行业务操作
        double operations=Double.parseDouble(data[3]);

        if(operations>0){//取款
            withdrawMoney(operations,data[0],data[1]);
        }
        else{//存款
            depositMoney(operations,data[0],data[1]);
        }
    }
    public void depositMoney(double operations,String CardID,String password){//存入钱

        if(this.bank.passwordIsCorrect(password)){//判断密码是否正确
            this.bank.SearchAccount(CardID).depositMoney(operations);
        }
    }
    public void withdrawMoney(double operations,String CardID,String password){
        if(this.bank.passwordIsCorrect(password)){//判断密码是否正确
            this.bank.SearchAccount(CardID).withdrawMoney(operations);
        }
    }
    public void setBank(Bank bank) {
        this.bank = bank;
    }

    public Bank getBank() {
        return bank;
    }

    public void setATMNumber(String ATMNumber) {
        this.ATMNumber = ATMNumber;
    }

    public String getATMNumber() {
        return ATMNumber;
    }
    public void showBalance(String[] data){//输出余额
        System.out.printf("当前余额为¥"+"%.2f\n",this.bank.SearchAccount(data[0]).getDeposit());

    }
    public void showBalance(String CardIDNumber){//输出余额
        System.out.printf("当前余额为¥"+"%.2f\n",this.bank.SearchAccount(CardIDNumber).getDeposit());
    }

    public void showOperations(String[] data){//输出操作
        if(Double.parseDouble(data[3])>0){
            System.out.printf(this.bank.SearchAccount(data[0]).getCardArrayList().get(0).getOwnerName()+"在"+this.bank.getBankName()+"的"+data[2]+"号ATM机上取款¥"+"%.2f\n",Math.abs(Double.parseDouble(data[3])));

        }
        else{
            System.out.printf(this.bank.SearchAccount(data[0]).getCardArrayList().get(0).getOwnerName()+"在"+this.bank.getBankName()+"的"+data[2]+"号ATM机上存款¥"+"%.2f\n",Math.abs(Double.parseDouble(data[3])));

        }
    }


}
class Bank{
    private String bankName;//银行名称
    private ArrayList<User>userArrayList=new ArrayList<>();//用户集合
    private ArrayList<ATM>atmArrayList=new ArrayList<>();//ATM机集合
    Bank(String bankName){
        this.bankName=bankName;
    }

    public void addUser(User user){//添加用户到集合中
        this.userArrayList.add(user);
    }

    public void addATM(ATM atm){//添加ATM机到集合中
        this.atmArrayList.add(atm);
    }
    public void setBankName(String bankName) {
        this.bankName = bankName;
    }

    public String getBankName() {
        return bankName;
    }

    public void setAtmArrayList(ArrayList<ATM> atmArrayList) {
        this.atmArrayList = atmArrayList;
    }

    public void setUserArrayList(ArrayList<User> userArrayList) {
        this.userArrayList = userArrayList;
    }

    public ArrayList<ATM> getAtmArrayList() {
        return atmArrayList;
    }

    public ArrayList<User> getUserArrayList() {
        return userArrayList;
    }
    public boolean passwordIsCorrect(String password){//密码是否正确
        for(int i=0;i<userArrayList.size();i++){
            for(int j=0;j<userArrayList.get(i).getAccountArrayList().size();j++){
                for(int k=0;k<userArrayList.get(i).getAccountArrayList().get(j).getCardArrayList().size();k++){
                    if(userArrayList.get(i).getAccountArrayList().get(j).getCardArrayList().get(k).getPassword().equals(password)){
                        return true;
                    }
                }
            }
        }
        System.out.println("Sorry,your password is wrong.");
        System.exit(0);
        return false;
    }
    public Account SearchAccount(String CardID){//搜素账户
        for(int i=0;i<userArrayList.size();i++){
            for(int j=0;j<userArrayList.get(i).getAccountArrayList().size();j++){
                for(int k=0;k<userArrayList.get(i).getAccountArrayList().get(j).getCardArrayList().size();k++){
                    if(userArrayList.get(i).getAccountArrayList().get(j).getCardArrayList().get(k).getCardId().equals(CardID)){
                        return userArrayList.get(i).getAccountArrayList().get(j);
                    }
                }
            }
        }
        Account account=new Account();
        return account;
    }

}
class ChinaUnionPay{
    ArrayList<Bank> bankArrayList=new ArrayList<>();
    ChinaUnionPay(){
        super();
        addBankInArrayList("中国建设银行");
        addBankInArrayList("中国工商银行");
        addUserData();//添加用户信息
        addATMData();//添加ATM机信息
    }


    public void addBankInArrayList(String bankName){//添加银行到集合中
        Bank bank=new Bank(bankName);
        this.bankArrayList.add(bank);

    }
    public Bank SearchBank(String bankName){//搜素银行
        for(int i=0;i<this.bankArrayList.size();i++){
            if(bankName.equals(this.bankArrayList.get(i).getBankName())){
                return this.bankArrayList.get(i);
            }
        }

        return this.bankArrayList.get(0);
    }//搜索遍历银行并返回

    public void addUserData(){//写入用户数据

        User user1=new User("杨过");
        Account account1=new Account("3217000010041315709",10000.0);
        Card card1=new Card("杨过","6217000010041315709","88888888",this.bankArrayList.get(0));
        Card card2=new Card("杨过","6217000010041315715","88888888",this.bankArrayList.get(0));
        Account account2=new Account("3217000010041315715",10000.0);
        Card card3=new Card("杨过","6217000010041315718","88888888",this.bankArrayList.get(0));
        account1.AddCard(card1);
        account1.AddCard(card2);
        account2.AddCard(card3);
        user1.AddAccount(account1);
        user1.AddAccount(account2);

        User user2=new User("郭靖");
        Account account3=new Account("3217000010051320007 ",10000.0);
        Card card4=new Card("郭靖","6217000010051320007","88888888",this.bankArrayList.get(0));
        account3.AddCard(card4);
        user2.AddAccount(account3);
        User user3=new User("张无忌");
        Account account4=new Account("3222081502001312389",10000.0);
        this.bankArrayList.get(0).addUser(user1);
        this.bankArrayList.get(0).addUser(user2);
        Card card5=new Card("张无忌","6222081502001312389","88888888",this.bankArrayList.get(1));
        account4.AddCard(card5);
        Account account5=new Account("3222081502001312390",10000.0);
        Card card6=new Card("张无忌","6222081502001312390","88888888",this.bankArrayList.get(1));
        account5.AddCard(card6);
        Account account6=new Account("3222081502001312399",10000.0);
        Card card7=new Card("张无忌","6222081502001312399","88888888",this.bankArrayList.get(1));
        Card card8=new Card("张无忌","6222081502001312400","88888888",this.bankArrayList.get(1));
        account6.AddCard(card7);
        account6.AddCard(card8);
        user3.AddAccount(account4);
        user3.AddAccount(account5);
        user3.AddAccount(account6);
        User user4=new User("韦小宝");
        Account account7=new Account("3222081502051320785",10000.0);
        Card card9=new Card("韦小宝","6222081502051320785","88888888",this.bankArrayList.get(1));
        account7.AddCard(card9);
        Account account8=new Account("3222081502051320786",10000.0);
        Card card10=new Card("韦小宝","6222081502051320786","88888888",this.bankArrayList.get(1));
        account8.AddCard(card10);
        user4.AddAccount(account7);
        user4.AddAccount(account8);
        this.bankArrayList.get(1).addUser(user3);
        this.bankArrayList.get(1).addUser(user4);


    }//添加用户信息

    public void addATMData(){
        ATM atm=new ATM("01",bankArrayList.get(0));
        ATM atm1=new ATM("02",bankArrayList.get(0));
        ATM atm2=new ATM("03",bankArrayList.get(0));
        ATM atm3=new ATM("04",bankArrayList.get(0));

        this.bankArrayList.get(0).addATM(atm);
        this.bankArrayList.get(0).addATM(atm1);
        this.bankArrayList.get(0).addATM(atm2);
        this.bankArrayList.get(0).addATM(atm3);

        ATM atm4=new ATM("05",bankArrayList.get(1));
        ATM atm5=new ATM("06",bankArrayList.get(1));
        this.bankArrayList.get(1).addATM(atm4);
        this.bankArrayList.get(1).addATM(atm5);

    }//添加ATM机信息

    public ATM SearchATM(String ATMNumber){
        for(int i=0;i<bankArrayList.size();i++){
            for(int j=0;j<bankArrayList.get(i).getAtmArrayList().size();j++){
                if(bankArrayList.get(i).getAtmArrayList().get(j).getATMNumber().equals(ATMNumber)){
                    return bankArrayList.get(i).getAtmArrayList().get(j);
                }
            }
        }

        System.out.println("Sorry,the ATM's id is wrong.");
        System.exit(0);
        ATM atm=new ATM();
        return atm;
    }
    public void showBalance(String CardID){//输出余额
        for(int i=0;i<bankArrayList.size();i++){
            for(int j=0;j<bankArrayList.get(i).getUserArrayList().size();j++){
                for(int k=0;k<bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().size();k++){
                    for(int l=0;l<bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k).getCardArrayList().size();l++){
                        if(bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k).getCardArrayList().get(l).getCardId().equals(CardID)){
                            System.out.printf("¥"+"%.2f\n",bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k).getDeposit());
                        }
                    }
                }
            }
        }
    }

    public boolean isCrossBank(ATM atm,String CardID){//是否跨银行
        for(int i=0;i<searchAccount(CardID).getCardArrayList().size();i++){
            if(searchAccount(CardID).getCardArrayList().get(i).getCardId().equals(CardID)){
                if(searchAccount(CardID).getCardArrayList().get(i).getBank().getBankName().equals(atm.getBank().getBankName())){
                    return false;
                }
            }
        }
        return true;
    }
public Account searchAccount(String CardID){//搜索账户
        for(int i=0;i<bankArrayList.size();i++){
            for(int j=0;j<bankArrayList.get(i).getUserArrayList().size();j++){
                for(int k=0;k<bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().size();k++){
                    for(int l=0;l<bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k).getCardArrayList().size();l++){
                        if(bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k).getCardArrayList().get(l).getCardId().equals(CardID)){
                            return bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k);
                        }
                    }
                }
            }
        }
        Account account=new Account();
        return account;
    }//搜索账户
    public boolean validCardID(String CardID){
        for(int i=0;i<bankArrayList.size();i++){
            for(int j=0;j<bankArrayList.get(i).getUserArrayList().size();j++){
                for(int k=0;k<bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().size();k++){
                    for(int l=0;l<bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k).getCardArrayList().size();l++){
                        if(bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k).getCardArrayList().get(l).getCardId().equals(CardID)){
                            return true;
                        }
                    }
                }
            }
        }

        return false;
    }


}

生成报表
Metrics Details For File 'java.txt'

Parameter Value
========= =====
Project Directory C:\Users\www\Desktop
Project Name
Checkpoint Name Baseline
File Name java.txt
Lines 472
Statements 260
Percent Branch Statements 15.4
Method Call Statements 214
Percent Lines with Comments 9.7
Classes and Interfaces 7
Methods per Class 8.43
Average Statements per Method 3.81
Line Number of Most Complex Method 300
Name of Most Complex Method ChinaUnionPay.ChinaUnionPay()
Maximum Complexity 13
Line Number of Deepest Block 410
Maximum Block Depth 8
Average Block Depth 2.09
Average Complexity 2.10


Most Complex Methods in 6 Class(es): Complexity, Statements, Max Depth, Calls

Account.Account() 1, 2, 2, 0
Account.Account() 1, 0, 0, 0
Account.AddCard() 1, 0, 0, 0
Account.depositMoney() 1, 0, 0, 0
Account.getAccountNumber() 1, 1, 2, 0
Account.getCardArrayList() 1, 1, 2, 0
Account.getDeposit() 1, 1, 2, 0
Account.setAccountNumber() 1, 1, 2, 0
Account.setCardArrayList() 1, 1, 2, 0
Account.setDeposit() 1, 1, 2, 0
Account.withdrawMoney() 1, 2, 2, 2
ATM.ATM() 1, 2, 2, 0
ATM.ATM() 1, 1, 2, 1
ATM.businessOperations() 3, 5, 3, 2
ATM.depositMoney() 2, 2, 3, 2
ATM.getATMNumber() 1, 1, 2, 0
ATM.getBank() 1, 1, 2, 0
ATM.setATMNumber() 1, 1, 2, 0
ATM.setBank() 1, 1, 2, 0
ATM.showBalance() 1, 1, 2, 1
ATM.showOperations() 3, 4, 3, 5
ATM.withdrawMoney() 2, 2, 3, 2
ChinaUnionPay().addATMData() 1, 12, 3, 12
ChinaUnionPay().addBankInArrayList() 1, 2, 3, 1
ChinaUnionPay().addUserData() 1, 28, 3, 20
ChinaUnionPay().isCrossBank() 3, 3, 5, 13
ChinaUnionPay().SearchATM() 4, 8, 6, 12
ChinaUnionPay().SearchBank() 3, 4, 5, 5
ChinaUnionPay().showBalance() 6, 6, 8, 27
ChinaUnionPay.ChinaUnionPay() 13, 4, 5, 13
ChinaUnionPay.searchAccount() 6, 8, 7, 26
ChinaUnionPay.validCardID() 6, 7, 7, 25
Main.main() 5, 20, 4, 10
User.AddAccount() 1, 1, 2, 1
User.getAccountArrayList() 1, 1, 2, 0
User.getUserName() 1, 1, 2, 0
User.setAccountArrayList() 1, 1, 2, 0
User.setUserName() 1, 1, 2, 0
User.User() 1, 1, 2, 0
User.User() 1, 0, 0, 0


Block Depth Statements

0 27
1 77
2 58
3 70
4 12
5 8
6 4
7 3
8 1
9+ 0

踩坑心得

这一题比较简单,因为实现的功能比较简单,但是在跨行取钱这里,出了问题,导致后面的继承处理跨行取钱的时候全错了。然后是各个类之间的关系太复杂了,生成类图后都很多连线。

改进建议

第一个就是简化类之间的关系,添加接口和抽象类可以简化,让代码可读性高一点,对后面的扩展也更友好,增加扩展性。

7-5 ATM机类结构设计(二)

设计与分析:

类图:

具体代码

import java.util.*;
public class Main {
    public static void main(String[]args){
        ChinaUnionPayNew chinaUnionPay=new ChinaUnionPayNew();
        Scanner in=new Scanner(System.in);
        String data=new String();
        data=in.nextLine();
        while(!data.equals("#")){
            String dataSplit[]=data.split("\\s{1,}");
            ATM atm=new ATM();
            if(dataSplit.length==1){
                chinaUnionPay.showBalance(dataSplit[0]);
            }
            else{
                atm=chinaUnionPay.SearchATM(dataSplit[2]);
                if(!chinaUnionPay.validCardID(dataSplit[0])){
                    System.out.println("Sorry,this card does not exist.");
                    System.exit(0);
                }
                if(chinaUnionPay.isCrossBank(atm,dataSplit[0])){
                    chinaUnionPay.CrossBankBusinessOperations(dataSplit);
                }
                else{
                    atm.businessOperations(dataSplit);
                    atm.showOperations(dataSplit);
                    atm.showBalance(dataSplit);
                }
            }
            data=in.nextLine();
        }
    }
}
class User{
    private String UserName;
    ArrayList<Account>accountArrayList=new ArrayList<>();
    User(){
    }
    User(String UserName){
        this.UserName=UserName;
    }
    public void addAccount(Account account){
        this.accountArrayList.add(account);
    }


    public String getUserName() {
        return UserName;
    }
    public void setUserName(String userName) {
        UserName = userName;
    }

    public void setAccountArrayList(ArrayList<Account> accountArrayList) {
        this.accountArrayList = accountArrayList;
    }

    public ArrayList<Account> getAccountArrayList() {
        return accountArrayList;
    }
}
class Account {
    private String accountPattern=new String();
    private String AccountNumber;//银行账号
    private double deposit;//存款
    ArrayList<Card> cardArrayList=new ArrayList<>();
    Account(){
        super();
    }
    Account(String AccountNumber,double deposit){
        super();
        this.AccountNumber=AccountNumber;
        this.deposit=deposit;
    }
    public double getDeposit() {
        return deposit;
    }
    public void setDeposit(double deposit) {
        this.deposit = deposit;
    }
    public void addCard(Card card){
        this.cardArrayList.add(card);
    }
    public ArrayList<Card> getCardArrayList() {
        return cardArrayList;
    }
    public void setAccountNumber(String accountNumber) {
        AccountNumber = accountNumber;
    }
    public void depositMoney(double operations){//存入
        this.deposit-=operations;
    }
    public void withdrawMoney(double operations){//取出
        if(operations>this.getDeposit()){
            if(this.accountPattern.equals("贷记")&&operations< 50000.0+Math.abs(this.deposit)){
                this.deposit-=operations*1.05;
            }
            else {
                System.out.println("Sorry,your account balance is insufficient.");
                System.exit(0);
            }
        }
        else{
            this.deposit-=operations;
        }
        if(this.getDeposit()<-50000.0){
            System.out.println("Sorry,your account balance is insufficient.");
            System.exit(0);
        }
    }
    public void withdrawMoney(double operations,double interbankWithdrawalServiceFee,String accountPattern){
        if(operations>this.getDeposit()){
            if(accountPattern.equals("贷记")){
                if(this.getDeposit()>0&&operations>this.getDeposit()&&operations<Math.abs(this.getDeposit())+50000.0){
                    this.deposit-=operations+(operations)*interbankWithdrawalServiceFee+(operations-this.getDeposit())*0.05;
                }
                else if(this.getDeposit()<0&&operations<Math.abs(this.getDeposit())+50000.0){
                    this.deposit-=operations*(1+0.05+interbankWithdrawalServiceFee);
                }
                else{
                    System.out.println("Sorry,your account balance is insufficient.");
                    System.exit(0);
                }
            }
            else{
                System.out.println("Sorry,your account balance is insufficient.");
                System.exit(0);
            }
        }
        else{
            this.deposit-=(operations*(1+interbankWithdrawalServiceFee));
        }
        if(Math.abs(this.getDeposit())>50000.0){
            System.out.println("Sorry,your account balance is insufficient.");
            System.exit(0);
        }
    }
    public String getAccountPattern() {
        return accountPattern;
    }
    public void setAccountPattern(String accountPattern) {
        this.accountPattern = accountPattern;
    }
}
class AccountNew extends Account{
    AccountNew(){
        super();
    }
    AccountNew(String AccountNumber,double deposit,String accountPattern){
        super();
        super.setAccountPattern(accountPattern);
        setAccountNumber(AccountNumber);
        setDeposit(deposit);
    }
}
class Card{
    private String CardId;//卡号
    private String password;//密码
    private Bank bank;//银行
    private String ownerName;
    Card(){
        super();
    }
    Card(String ownerName,String CardId,String password,Bank bank){
        super();
        this.bank=bank;
        this.password=password;
        this.CardId=CardId;
        this.ownerName=ownerName;
    }

    public void setBank(Bank bank) {
        this.bank = bank;
    }

    public void setCardId(String cardId) {
        CardId = cardId;
    }


    public void setPassword(String password) {
        this.password = password;
    }

    public Bank getBank() {
        return bank;
    }



    public String getCardId() {
        return CardId;
    }

    public String getPassword() {
        return password;
    }


    public void setOwnerName(String ownerName) {
        this.ownerName = ownerName;
    }

    public String getOwnerName() {
        return ownerName;
    }
}
class ATM{
    private String ATMNumber;
    private Bank bank;
    ATM(){
        super();
    }
    ATM(String ATMNumber,Bank bank){
        this.ATMNumber=ATMNumber;
        this.bank=bank;
    }
    public void businessOperations(String[] data){
        double operations=Double.parseDouble(data[3]);

        if(operations>0){//取款
            withdrawMoney(operations,data[0],data[1]);
        }
        else{//存款
            depositMoney(operations,data[0],data[1]);
        }
    }//进行业务操作
    public void depositMoney(double operations,String CardID,String password){
        if(this.bank.passwordIsCorrect(password,CardID)){//判断密码是否正确
            this.bank.searchAccount(CardID).depositMoney(operations);
        }
        else{
            printfPasswordWrong();
        }
    }
    public void withdrawMoney(double operations,String CardID,String password){
        if(this.bank.passwordIsCorrect(password,CardID)){//判断密码是否正确
            this.bank.searchAccount(CardID).withdrawMoney(operations);
        }
        else{
            printfPasswordWrong();
        }
    }
    public void printfPasswordWrong(){
        System.out.println("Sorry,your password is wrong.");
        System.exit(0);
    }
    public Bank getBank() {
        return bank;
    }
    public String getATMNumber() {
        return ATMNumber;
    }
    public void showBalance(String[] data){
        System.out.printf("当前余额为¥"+"%.2f\n",this.bank.searchAccount(data[0]).getDeposit());
    }
    public void showOperations(String[] data){
        if(Double.parseDouble(data[3])>0){
            printfOperations(data,"取款");
        }
        else{
            printfOperations(data,"存款");
        }
    }
    public void printfOperations(String[] data,String operations){
        System.out.printf("业务:"+operations+" "+this.bank.searchAccount(data[0]).getCardArrayList().get(0).getOwnerName()+"在"+this.bank.getBankName()+"的"+data[2]+"号ATM机上"+operations+"¥"+"%.2f\n",Math.abs(Double.parseDouble(data[3])));
    }
}
class Bank{
    private String bankName;
    private ArrayList<User>userArrayList=new ArrayList<>();
    private ArrayList<ATM>atmArrayList=new ArrayList<>();
    Bank(){
    }
    Bank(String bankName){
        this.bankName=bankName;
    }
    public void addUser(User user){
        this.userArrayList.add(user);
    }
    public void addATM(ATM atm){
        this.atmArrayList.add(atm);
    }
    public void setBankName(String bankName) {
        this.bankName = bankName;
    }
    public String getBankName() {
        return bankName;
    }
    public void setAtmArrayList(ArrayList<ATM> atmArrayList) {
        this.atmArrayList = atmArrayList;
    }
    public void setUserArrayList(ArrayList<User> userArrayList) {
        this.userArrayList = userArrayList;
    }
    public ArrayList<ATM> getAtmArrayList() {
        return atmArrayList;
    }
    public ArrayList<User> getUserArrayList() {
        return userArrayList;
    }
    public boolean passwordIsCorrect(String password,String CardID){
        for(int i=0;i<searchAccount(CardID).getCardArrayList().size();i++){
            if(searchAccount(CardID).getCardArrayList().get(i).getPassword().equals(password)){
                return true;
            }
        }
        System.out.println("Sorry,your password is wrong.");
        System.exit(0);
        return false;
    }
    public Account searchAccount(String CardID){
        for(int i=0;i<userArrayList.size();i++){
            for(int j=0;j<userArrayList.get(i).getAccountArrayList().size();j++){
                for(int k=0;k<userArrayList.get(i).getAccountArrayList().get(j).getCardArrayList().size();k++){
                    if(userArrayList.get(i).getAccountArrayList().get(j).getCardArrayList().get(k).getCardId().equals(CardID)){
                        return userArrayList.get(i).getAccountArrayList().get(j);
                    }
                }
            }
        }
        return new Account();
    }//搜索账户
}
class BankNew extends Bank{
    private double interbankWithdrawalServiceFee;//跨行取款手续费
    BankNew(String bankName,double interbankWithdrawalServiceFee){
        super();
        this.interbankWithdrawalServiceFee=interbankWithdrawalServiceFee;
        super.setBankName(bankName);
        super.getUserArrayList();
        super.getAtmArrayList();
    }
    BankNew(){
        super();
    }
    public String getBankName() {
        return super.getBankName();
    }
    public void setAtmArrayList(ArrayList<ATM> atmArrayList) {
        super.setAtmArrayList(atmArrayList);
    }
    public ArrayList<ATM> getAtmArrayList() {
        return super.getAtmArrayList();
    }
    public void setBankName(String bankName) {
        super.setBankName(bankName);
    }
    public void setUserArrayList(ArrayList<User> userArrayList) {
        super.setUserArrayList(userArrayList);
    }
    public void setInterbankWithdrawalServiceFee(double interbankWithdrawalServiceFee) {
        this.interbankWithdrawalServiceFee = interbankWithdrawalServiceFee;
    }
    public ArrayList<User> getUserArrayList() {
        return super.getUserArrayList();
    }
    public double getInterbankWithdrawalServiceFee() {
        return interbankWithdrawalServiceFee;
    }
}
class ChinaUnionPay{
    ArrayList<Bank> bankArrayList=new ArrayList<>();
    ChinaUnionPay(){
        super();
        addBankInArrayList("中国建设银行");
        addBankInArrayList("中国工商银行");
        addUserData();//添加用户信息
        addATMData();//添加ATM机信息
    }

    public ArrayList<Bank> getBankArrayList() {
        return bankArrayList;
    }
    public void addBankInArrayList(String bankName){
        Bank bank=new Bank(bankName);
        this.bankArrayList.add(bank);
    }
    public void addUserData(){
        User user1=new User("杨过");
        Account account1=createAccount("3217000010041315709");
        Card card1=createCard("杨过","6217000010041315709",0);
        Card card2=createCard("杨过","6217000010041315715",0);
        Account account2=createAccount("3217000010041315715");
        Card card3=  createCard("杨过","6217000010041315718",0);
        account1.addCard(card1);
        account1.addCard(card2);
        account2.addCard(card3);
        user1.addAccount(account1);
        user1.addAccount(account2);
        User user2=new User("郭靖");
        Account account3=createAccount("3217000010051320007");
        Card card4= createCard("郭靖","6217000010051320007",1);
        account3.addCard(card4);
        user2.addAccount(account3);
        User user3=new User("张无忌");
        Account account4=createAccount("3222081502001312389");
        this.bankArrayList.get(0).addUser(user1);
        this.bankArrayList.get(0).addUser(user2);
        Card card5=createCard("张无忌","6222081502001312389",1);
        account4.addCard(card5);
        Account account5=createAccount("3222081502001312390");
        Card card6=createCard("张无忌","6222081502001312390",1);
        account5.addCard(card6);
        Account account6=createAccount("3222081502001312399");
        Card card7=createCard("张无忌","6222081502001312399",1);
        Card card8=createCard("张无忌","6222081502001312400",1);
        account6.addCard(card7);
        account6.addCard(card8);
        user3.addAccount(account4);
        user3.addAccount(account5);
        user3.addAccount(account6);
        User user4=new User("韦小宝");
        Account account7=createAccount("3222081502051320785");
        Card card9=createCard("韦小宝","6222081502051320785",1);
        account7.addCard(card9);
        Account account8=createAccount("3222081502051320786");
        Card card10=createCard("韦小宝","6222081502051320786",1);
        account8.addCard(card10);
        user4.addAccount(account7);
        user4.addAccount(account8);
        this.bankArrayList.get(1).addUser(user3);
        this.bankArrayList.get(1).addUser(user4);
    }//添加用户信息
    public Account createAccount(String accountNumber){
        Account account=new Account(accountNumber,10000.0);
        return account;
    }
    public Card createCard(String ownerName,String Card ,int bankName){
        Card card=new Card(ownerName,Card,"88888888",this.bankArrayList.get(bankName));
        return card;
    }
    public void addATMData(){
        addNewATMDataOne(0,"01");
        addNewATMDataOne(0,"02");
        addNewATMDataOne(0,"03");
        addNewATMDataOne(0,"04");
        addNewATMDataOne(1,"05");
        addNewATMDataOne(1,"06");
    }//添加ATM机信息
    public void addNewATMDataOne(int bankNumber,String ATMNumber){
        getBankArrayList().get(bankNumber).getAtmArrayList().add(creatATM(ATMNumber,getBankArrayList().get(bankNumber)));
    }
    public ATM creatATM(String ATMNumber,Bank bank){
        ATM atm =new ATM(ATMNumber,bank);
        return atm;
    }
    public ATM SearchATM(String ATMNumber){
        for(int i=0;i<bankArrayList.size();i++){
            for(int j=0;j<bankArrayList.get(i).getAtmArrayList().size();j++){
                if(bankArrayList.get(i).getAtmArrayList().get(j).getATMNumber().equals(ATMNumber)){
                    return bankArrayList.get(i).getAtmArrayList().get(j);
                }
            }
        }
        System.out.println("Sorry,the ATM's id is wrong.");
        System.exit(0);
        ATM atm=new ATM();
        return atm;
    }
    public double getBalance(String CardID){
        return searchAccount(CardID).getDeposit();
    }
    public boolean isCrossBank(ATM atm,String CardID){
        for(int i=0;i<searchAccount(CardID).getCardArrayList().size();i++){
            if(searchAccount(CardID).getCardArrayList().get(i).getCardId().equals(CardID)){
                if(searchAccount(CardID).getCardArrayList().get(i).getBank().getBankName().equals(atm.getBank().getBankName())){
                    return false;
                }
            }
        }
        return true;
    }
    public Account searchAccount(String CardID){
        for(int i=0;i<bankArrayList.size();i++){
            for(int j=0;j<bankArrayList.get(i).getUserArrayList().size();j++){
                for(int k=0;k<bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().size();k++){
                    for(int l=0;l<bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k).getCardArrayList().size();l++){
                        if(bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k).getCardArrayList().get(l).getCardId().equals(CardID)){
                            return bankArrayList.get(i).getUserArrayList().get(j).getAccountArrayList().get(k);
                        }
                    }
                }
            }
        }
        return new Account();
    }//搜索账户
    public boolean validCardID(String CardID){
        for(int i=0;i<searchAccount(CardID).getCardArrayList().size();i++){
            if(searchAccount(CardID).getCardArrayList().get(i).getCardId().equals(CardID)){
                return true;
            }
        }
        return false;
    }
}
class ChinaUnionPayNew extends ChinaUnionPay{
    ArrayList<BankNew>bankNewArrayList=new ArrayList<>();
    ChinaUnionPayNew(){
        super();
        BankNew bank=new BankNew("中国农业银行",0.04);
        BankNew bankNew1=new BankNew("中国建设银行",0.02);
        BankNew bankNew2=new BankNew("中国工商银行",0.03);
        super.getBankArrayList().add(bank);
        super.getBankArrayList().set(0,bankNew1);
        super.getBankArrayList().set(1,bankNew2);
        getBankNewArrayList().add(bankNew1);
        getBankNewArrayList().add(bankNew2);
        getBankNewArrayList().add(bank);
        super.addATMData();
        super.addUserData();
        addNewUserData();
        addNewATMData();
    }
    public ArrayList<BankNew> getBankNewArrayList() {
        return bankNewArrayList;
    }
      public void CrossBankBusinessOperations(String[] data){
        double operations=Double.parseDouble(data[3]);
        Account account=new AccountNew();
        AccountNew accountNew=new AccountNew();
        account=super.searchAccount(data[0]);
        if(operations>0){//取款
            withdrawMoney(operations,data[0],data[1],account,data[2]);
        }
        else{//存款
            depositMoney(operations,data[0],data[1],account);
        }
        showOperations(data);
        showBalance(account);
    }
    public void showBalance(Account account){
        System.out.printf("当前余额为¥"+"%.2f\n",account.getDeposit());
    }
    public void showOperations(String[] data){
        String ATMNumber=data[2];
        if(Double.parseDouble(data[3])>0){
            System.out.printf("业务:取款 "+super.searchAccount(data[0]).getCardArrayList().get(0).getOwnerName()+"在"+searchBank(ATMNumber).getBankName()+"的"+data[2]+"号ATM机上取款¥"+"%.2f\n",Math.abs(Double.parseDouble(data[3])));
        }
        else{
            System.out.printf("业务:取款 "+super.searchAccount(data[0]).getCardArrayList().get(0).getOwnerName()+"在"+searchBank(ATMNumber).getBankName()+"的"+data[2]+"号ATM机上存款¥"+"%.2f\n",Math.abs(Double.parseDouble(data[3])));
        }
    }
    public void depositMoney(double operations,String CardID,String password,Account account){
        for(int i=0;i<account.getCardArrayList().size();i++){
            if(account.getCardArrayList().get(i).getPassword().equals(password)){//判断密码是否正确
                account.depositMoney(operations);
            }
            else{
                printfPasswordWrong();
            }
        }
    }
    public void withdrawMoney(double operations,String CardID,String password,Account account,String ATMNumber){

        for(int i=0;i<account.getCardArrayList().size();i++){
            if(account.getCardArrayList().get(i).getPassword().equals(password)){//判断密码是否正确
                account.withdrawMoney(operations,searchBank(ATMNumber).getInterbankWithdrawalServiceFee(),account.getAccountPattern());
                break;
            }
            else{
                printfPasswordWrong();
            }
        }
    }
    public void printfPasswordWrong(){
        System.out.println("Sorry,your password is wrong.");
        System.exit(0);
    }
    public BankNew searchBank(String ATMNumber){
        for(int i=0;i<bankArrayList.size();i++){
            for(int j=0;j<bankArrayList.get(i).getAtmArrayList().size();j++){
                if(bankArrayList.get(i).getAtmArrayList().get(j).getATMNumber().equals(ATMNumber)){
                    return bankNewArrayList.get(i);
                }
            }
        }
        return new BankNew();
    }
    public void showBalance(String CardID){
        System.out.printf("业务:查询余额 ¥%.2f\n",getBalance(CardID));
    }
    public void addNewATMData(){
        addNewATMDataOne(2,"07");
        addNewATMDataOne(2,"08");
        addNewATMDataOne(2,"09");
        addNewATMDataOne(2,"10");
        addNewATMDataOne(2,"11");
    }
    public void addNewATMDataOne(int bankNumber,String ATMNumber){
        super.getBankArrayList().get(bankNumber).getAtmArrayList().add(super.creatATM(ATMNumber,super.getBankArrayList().get(bankNumber)));
    }
    public void addNewUserData(){
        User user=new User("张三丰");
        Account account=new AccountNew("3640000010045442002",10000.0,"贷记");
        Card card=new Card("张三丰","6640000010045442002","88888888",super.getBankArrayList().get(0));
        Card card1=new Card("张三丰","6640000010045442003","88888888",super.getBankArrayList().get(0));
        account.addCard(card);
        account.addCard(card1);
        user.addAccount(account);
        User user1=new User("令狐冲 ");
        Account account1=new AccountNew("3640000010045441009",10000.0,"贷记");
        Card card2=new Card("令狐冲","6640000010045441009","88888888",super.getBankArrayList().get(1));
        account1.addCard(card2);
        user1.addAccount(account1);
        User user2=new User("乔峰 ");
        Account account2=new AccountNew("3630000010033431001",10000.0,"贷记");
        Card card3=new Card("乔峰","6630000010033431001","88888888",super.getBankArrayList().get(2));
        account2.addCard(card3);
        user2.addAccount(account2);
        User user3=new User("洪七公");
        Account account3=new AccountNew("3630000010033431008",10000.0,"贷记");
        Card card4=new Card("洪七公","6630000010033431008","88888888",super.getBankArrayList().get(2));
        account3.addCard(card4);
        user3.addAccount(account3);
        super.getBankArrayList().get(0).addUser(user);
        super.getBankArrayList().get(1).addUser(user1);
        super.getBankArrayList().get(2).addUser(user2);
        super.getBankArrayList().get(2).addUser(user3);
    }
}

踩坑心得

这题有点难,我在这题上的考虑可能过多了,导致后面的代码有点臃肿。每个类的关系也有点复杂。可能是一开始没有规划好类之间的关系,导致后面实现不同的功能的时候,受到各个类的影响。导致实现不了。就像后面有个账号后面加了一个卡的类型,继承下来后就又与之前的冲突了。

改进建议

在原有的基础上,重新规划类之间的关系。添加接口或者抽象类来满足后面的要求。

总结:

这三次的作业集从开始对单条数据的操作再到多多条数据,再到对多条数据分别作出不同的操作。以及正则表达式的熟练与运用。还有类的聚合和组合,还有到后面的继承都在类的关系上熟练。后来的作业集也是结合了现实里的例子来写,虽然后面最后一个ATM的题目没有拿到满分,有点遗憾。总结来说,这三次题目使用面向对象的设计原则,例如封装、继承和多态性,也遵循了七大设计原则中的单一职责原则,ATM(2)遵循了开闭原则,合成复用原则,最后可能没有很好的遵循迪米特法则,所以导致后面的ATM没有得满分。

posted @ 2023-04-26 23:35  开心不能伤心  阅读(128)  评论(0编辑  收藏  举报