OOP课程题目集第二次总结
前言
本次总结针对于pta上第二阶段的三次题目集。
第四次题目集主要训练Java的封装性以及一些常见的字符串处理,题量不多,部分题目较难;
第五次题目集主要训练正则表达式,和类之间的聚合关系,题量不多,比较简单;
第六次作业主要训练继承,多态和类之间的组合关系,题量少,难度一般;
本次总结将对部分难题和所遇见的问题进行一次分析和总结。
设计与分析
下面对三次题目集的部分题目进行设计与分析。
4-1菜单计价程序-3
题面较长,列出主要任务,逐个任务完成。
- 记录菜单
- 获取并储存订单记录
- 日期及打折有关处理
- 带点餐功能
- 对订单进行价格计算
- 输出价格
- 对错误订单进行报错处理
对于菜单的记录,用List存储
Mune类如下
class Menu{
public Menu() {
}
private static ArrayList<Dish> dishs =new ArrayList<Dish>();
public static Dish searthDish(String dishName){//懒的实例化对象,用了static
for(int i = 0;i<dishs.size();i++){
if(dishName.equals(dishs.get(i).getName())){
return dishs.get(i);
}
}
return null;
}
public static void addDish(String dishName,int unit_price){
Dish temp = new Dish(dishName,unit_price);
dishs.add(temp);
}
}
记录订单的代码如下
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
String[] menuMessages = new String[2];//存菜单信息的
while (!message.startsWith("table")) {//不断进行菜单获取和处理
menuMessages = message.split(" ");
if (Menu.searthDish(menuMessages[0]) != null) {//更新价格
Menu.searthDish(menuMessages[0]).setUnit_price(Integer.parseInt(menuMessages[1]));
message = scan.nextLine();
continue;
}
Menu.addDish(menuMessages[0], Integer.parseInt(menuMessages[1]));//添加菜单
message = scan.nextLine();
if(message.startsWith("end")){//结束
return;
}
}
获取并储存订单message,顺便在记录订单时处理delete信息
String[] tableMessages = new String[8];//存桌子信息
String[] deleteMessage = new String[2];//存删除信息
String[] recordMessages = new String[4];//存点单信息
String[] forMessages = new String[5];//代点单信息
int refond = 0;
while (!message.startsWith("end")) {//点单获取和处理
if (message.split(" ").length== 2&&!message.endsWith("delete")) {//更新菜单
menuMessages = message.split(" ");//存菜单信息的
if (Menu.searthDish(menuMessages[0]) != null) {//更新价格
Menu.searthDish(menuMessages[0]).setUnit_price(Integer.parseInt(menuMessages[1]));
} else {
Menu.addDish(menuMessages[0], Integer.parseInt(menuMessages[1]));
}
} else if (message.split(" ").length== 5) {//代点餐处理的
forMessages = message.split(" ");
order.addARecord(Integer.parseInt(forMessages[1]), forMessages[2], Integer.parseInt(forMessages[3]), Integer.parseInt(forMessages[4]));//添加record的
order.getRecords().get(order.getRecords().size()-1).setIsForOther(Integer.parseInt(forMessages[0]));
Order.times++;
} else if (message.startsWith("table")) {//table信息处理的
howManyTable++;
order.getRefund().add(refond);
refond = 0;
tableMessages = message.split(" |/");
tableDiscount.add(discount(tableMessages));
} else if (message.indexOf("delete") != -1) {//删除信息获取的
Order.times++;
deleteMessage = message.split(" ");
if(order.delARecordByOrderNum(Integer.parseInt(deleteMessage[0]))) {//处理delete的
for(int i = 0;i< order.getRecords().size();i++) {
if (order.getRecords().get(i).getOrderNum() == Integer.parseInt(deleteMessage[0])) {
refond += order.getRecords().get(Integer.parseInt(deleteMessage[0]) - 1).getD().getPrice(order.getRecords().get(Integer.parseInt(deleteMessage[0]) - 1).getPortion()) * order.getRecords().get(Integer.parseInt(deleteMessage[0]) - 1).getNum();
break;
}
}
}
} else if(message.split(" ").length== 4){//正常点餐的
Order.times++;
recordMessages = message.split(" ");
order.addARecord(Integer.parseInt(recordMessages[0]), recordMessages[1], Integer.parseInt(recordMessages[2]), Integer.parseInt(recordMessages[3]));//添加record的
}
message = scan.nextLine();
}
order.getRefund().add(refond);
订单获取到的信息存在Order里,Order的类如下
class Order {
private ArrayList<Record> records = new ArrayList<Record>();
private static ArrayList<Integer> refund = new ArrayList<Integer>();//delete退的钱
public static int times = 0;//客户操作次数
public ArrayList<Record> getRecords() {
return records;
}
public int getTotalPrice() {
int allPrice = 0;
return allPrice;
}
public static ArrayList<Integer> getRefund() {
return refund;
}
public void addARecord(int orderNum, String dishName, int portion, int num){
Record temp = new Record(orderNum,dishName,portion,num);
if(Menu.searthDish(dishName)!=null) {
temp.getD().setUnit_price(Menu.searthDish(dishName).getUnit_price());
records.add(temp);
}else{
records.add(temp);
}
}
public boolean delARecordByOrderNum(int orderNum) {//先默认返回void
for (int i = 0; i < records.size(); i++) {
if (records.get(i).getOrderNum() == (orderNum) && !getRecords().get(i).getIsdelete()) {
getRecords().get(orderNum - 1).setIsdelete(true);
return true;
}
}
Record temp = new Record(orderNum, null, 0, 0, true, true, 0);
records.add(temp);
return false;
}
}
对日期及打折有关处理
public static double discount(String[] tableMessages){//判断折扣
LocalDateTime theTime = LocalDateTime.of(Integer.parseInt(tableMessages[2]), Integer.parseInt(tableMessages[3]), Integer.parseInt(tableMessages[4]), Integer.parseInt(tableMessages[5]), Integer.parseInt(tableMessages[6]), Integer.parseInt(tableMessages[7]));//存时间
int whichDay = theTime.getDayOfWeek().getValue();//星期几
if (whichDay >= 1 && whichDay <= 5) {//不在周末
if (Integer.parseInt(tableMessages[5]) >= 17 && Integer.parseInt(tableMessages[5]) < 20 || Integer.parseInt(tableMessages[5]) == 20 && Integer.parseInt(tableMessages[6]) <= 30) {
return 0.8;
} else if (Integer.parseInt(tableMessages[5]) > 10 && Integer.parseInt(tableMessages[5]) < 14 || Integer.parseInt(tableMessages[5]) == 10 && Integer.parseInt(tableMessages[6]) >= 30 || Integer.parseInt(tableMessages[5]) == 14 && Integer.parseInt(tableMessages[6]) <= 30) {
return 0.6;
} else {//不在时间内
return -1.0;
}
} else {//在周末
if (Integer.parseInt(tableMessages[5]) > 9 && Integer.parseInt(tableMessages[5]) < 21 || Integer.parseInt(tableMessages[5]) == 9 && Integer.parseInt(tableMessages[6]) >= 30) {
return 1.0;
} else {
return -1.0;
}
}
}
带点餐功能,在存入Order时对该订单做标记,算价格时计算到对应桌
存入Order时标记
else if (message.split(" ").length== 5) {//代点餐处理的
forMessages = message.split(" ");
order.addARecord(Integer.parseInt(forMessages[1]), forMessages[2], Integer.parseInt(forMessages[3]), Integer.parseInt(forMessages[4]));//添加record的
order.getRecords().get(order.getRecords().size()-1).setIsForOther(Integer.parseInt(forMessages[0]));
Order.times++;//点单次数
}
价格计算
if (order.getRecords().get(i).getIsForOther() != 0) {//代点餐的
System.out.println(order.getRecords().get(i).getOrderNum() + " table " + (whichTable - 1) + " pay for table " + order.getRecords().get(i).getIsForOther() + " " + order.getRecords().get(i).getD().getPrice(order.getRecords().get(i).getPortion()) * order.getRecords().get(i).getNum());
}
对订单进行价格计算,并对错误订单进行报错处理,最后输出价格
public static void outputMessage(Order order,ArrayList<Double> tableDiscount,ArrayList<Integer> countTable) {
int whichTable = 1;//储存一共几桌
int count = 0;//计算价格的中介
for (int i = 0; i < order.getRecords().size(); i++) {//一条条处理record的
if (order.getRecords().get(i).getIsError()) {//删除错误的
System.out.println("delete error;");
continue;
}else if (order.getRecords().get(i).getD().getPrice(order.getRecords().get(i).getPortion()) != 0) {//正常输出的
if (order.getRecords().get(i).getIsForOther() != 0) {//代点餐的
System.out.println(order.getRecords().get(i).getOrderNum() + " table " + (whichTable - 1) + " pay for table " + order.getRecords().get(i).getIsForOther() + " " + order.getRecords().get(i).getD().getPrice(order.getRecords().get(i).getPortion()) * order.getRecords().get(i).getNum());
} else {
if (order.getRecords().get(i).getOrderNum() == 1) {
System.out.println("table " + whichTable + ": ");
countTable.add(count);
count = 0;
whichTable++;
}
System.out.print(order.getRecords().get(i).getOrderNum());
System.out.print(" " + order.getRecords().get(i).getD().getName() + " ");
System.out.println(order.getRecords().get(i).getD().getPrice(order.getRecords().get(i).getPortion()) * order.getRecords().get(i).getNum());
}
count += order.getRecords().get(i).getD().getPrice(order.getRecords().get(i).getPortion()) * order.getRecords().get(i).getNum();
} else {//delete不存在的
System.out.println(order.getRecords().get(i).getD().getName() + " does not exist");//无该桌报错
order.getRecords().get(i).setError(true);
}
}
countTable.add(count);
for (int i = 0; i < whichTable - 1; i++) {
if (tableDiscount.get(i) < 0.0) {
System.out.println("table " + (i + 1) + " out of opening hours");//不在时间内
continue;
}
System.out.println("table " + (i + 1) + ": " + (int) ((countTable.get(i + 1) - Order.getRefund().get(i+1)) * tableDiscount.get(i) + 0.5));
}
}
完整代码如下
import java.util.*;
import java.time.*;
class Dish{
private String name;//菜品名称
private int unit_price; //单价
public Dish(){
}
public Dish(String name){
this.name = name;
}
public Dish(String name,int unit_price){
this.name = name;
this.unit_price = unit_price;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setUnit_price(int unit_price){
this.unit_price = unit_price;
}
public int getUnit_price(){
return unit_price;
}
public int getPrice(int portion){
if(portion==1){
return unit_price;
}else if(portion==2){
return (int)(unit_price*1.5+0.5);
}else if(portion==3){
return unit_price*2;
}else{
return -1;
}
}
}
class Menu{
public Menu() {
}
private static ArrayList<Dish> dishs =new ArrayList<Dish>();
public static Dish searthDish(String dishName){//懒的实例化对象,用了static
for(int i = 0;i<dishs.size();i++){
if(dishName.equals(dishs.get(i).getName())){
return dishs.get(i);
}
}
return null;
}
public static void addDish(String dishName,int unit_price){
Dish temp = new Dish(dishName,unit_price);
dishs.add(temp);
}
}
class Record{
private int orderNum;
private Dish d = new Dish();
private int portion;
private int num;//记录几份
private boolean isError = false;
private boolean isdelete = false;
private int isForOther = 0;//代哪桌点菜
public Record() {
}
public Record(int orderNum, String name, int portion, int num) {
this.orderNum = orderNum;
this.d.setName(name);
this.portion = portion;
this.num = num;
}
public Record(int orderNum, Dish d, int portion, int num, boolean isError, boolean isdelete, int isForOther) {
this.orderNum = orderNum;
this.d = d;
this.portion = portion;
this.num = num;
this.isError = isError;
this.isdelete = isdelete;
this.isForOther = isForOther;
}
public boolean getIsdelete() {
return isdelete;
}
public void setIsdelete(boolean isdelete) {
this.isdelete = isdelete;
}
public int getOrderNum() {
return orderNum;
}
public void setOrderNum(int orderNum) {
this.orderNum = orderNum;
}
public Dish getD() {
return d;
}
public void setD(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;
}
public int getIsForOther() {
return isForOther;
}
public void setIsForOther(int isForOther) {
this.isForOther = isForOther;
}
private int getPrice(){
if(Menu.searthDish(d.getName())!= null){
d = Menu.searthDish(d.getName());
return d.getPrice(this.portion);
}else{
return -1;//未找到菜品
}
}
public boolean getIsError() {
return isError;
}
public void setError(boolean error) {
isError = error;
}
}
class Order {
private ArrayList<Record> records = new ArrayList<Record>();
private static ArrayList<Integer> refund = new ArrayList<Integer>();//delete退的钱
public static int times = 0;//客户操作次数
public ArrayList<Record> getRecords() {
return records;
}
public int getTotalPrice() {
int allPrice = 0;
return allPrice;
}
public static ArrayList<Integer> getRefund() {
return refund;
}
public void addARecord(int orderNum, String dishName, int portion, int num){
Record temp = new Record(orderNum,dishName,portion,num);
if(Menu.searthDish(dishName)!=null) {
temp.getD().setUnit_price(Menu.searthDish(dishName).getUnit_price());
records.add(temp);
}else{
records.add(temp);
}
}
public boolean delARecordByOrderNum(int orderNum) {//先默认返回void
for (int i = 0; i < records.size(); i++) {
if (records.get(i).getOrderNum() == (orderNum) && !getRecords().get(i).getIsdelete()) {
getRecords().get(orderNum - 1).setIsdelete(true);
return true;
}
}
Record temp = new Record(orderNum, null, 0, 0, true, true, 0);
records.add(temp);
return false;
}
}
public class Main {//尝试多个个table的试试
public static void main(String[] args) {
ArrayList<Integer> countTable = new ArrayList<Integer>();//记录总账
ArrayList<Double> tableDiscount = new ArrayList<Double>();//记录折扣
Order order = new Order();
inputMessage(order, tableDiscount);//处理输入信息的
outputMessage(order, tableDiscount,countTable);//处理输出的
}
public static void inputMessage(Order order,ArrayList<Double> tableDiscount){
int howManyTable = 0;
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
String[] menuMessages = new String[2];//存菜单信息的
while (!message.startsWith("table")) {//不断进行菜单获取和处理
menuMessages = message.split(" ");
if (Menu.searthDish(menuMessages[0]) != null) {//更新价格
Menu.searthDish(menuMessages[0]).setUnit_price(Integer.parseInt(menuMessages[1]));
message = scan.nextLine();
continue;
}
Menu.addDish(menuMessages[0], Integer.parseInt(menuMessages[1]));//添加菜单
message = scan.nextLine();
if(message.startsWith("end")){//结束
return;
}
}
String[] tableMessages = new String[8];//存桌子信息
String[] deleteMessage = new String[2];//存删除信息
String[] recordMessages = new String[4];//存点单信息
String[] forMessages = new String[5];//代点单信息
int refond = 0;
while (!message.startsWith("end")) {//点单获取和处理
if (message.split(" ").length== 2&&!message.endsWith("delete")) {//更新菜单
menuMessages = message.split(" ");//存菜单信息的
if (Menu.searthDish(menuMessages[0]) != null) {//更新价格
Menu.searthDish(menuMessages[0]).setUnit_price(Integer.parseInt(menuMessages[1]));
} else {
Menu.addDish(menuMessages[0], Integer.parseInt(menuMessages[1]));
}
} else if (message.split(" ").length== 5) {//代点餐处理的
forMessages = message.split(" ");
order.addARecord(Integer.parseInt(forMessages[1]), forMessages[2], Integer.parseInt(forMessages[3]), Integer.parseInt(forMessages[4]));//添加record的
order.getRecords().get(order.getRecords().size()-1).setIsForOther(Integer.parseInt(forMessages[0]));
Order.times++;//点单次数
} else if (message.startsWith("table")) {//table信息处理的
howManyTable++;
order.getRefund().add(refond);
refond = 0;
tableMessages = message.split(" |/");
tableDiscount.add(discount(tableMessages));
} else if (message.indexOf("delete") != -1) {//删除信息获取的
Order.times++;
deleteMessage = message.split(" ");
if(order.delARecordByOrderNum(Integer.parseInt(deleteMessage[0]))) {//处理delete的
for(int i = 0;i< order.getRecords().size();i++) {
if (order.getRecords().get(i).getOrderNum() == Integer.parseInt(deleteMessage[0])) {
refond += order.getRecords().get(Integer.parseInt(deleteMessage[0]) - 1).getD().getPrice(order.getRecords().get(Integer.parseInt(deleteMessage[0]) - 1).getPortion()) * order.getRecords().get(Integer.parseInt(deleteMessage[0]) - 1).getNum();
break;
}
}
}
} else if(message.split(" ").length== 4){//正常点餐的
Order.times++;
recordMessages = message.split(" ");
order.addARecord(Integer.parseInt(recordMessages[0]), recordMessages[1], Integer.parseInt(recordMessages[2]), Integer.parseInt(recordMessages[3]));//添加record的
}
message = scan.nextLine();
}
order.getRefund().add(refond);
}
public static void outputMessage(Order order,ArrayList<Double> tableDiscount,ArrayList<Integer> countTable) {
int whichTable = 1;
int count = 0;
for (int i = 0; i < order.getRecords().size(); i++) {//一条条处理record的
if (order.getRecords().get(i).getIsError()) {//删除错误的
System.out.println("delete error;");
continue;
}else if (order.getRecords().get(i).getD().getPrice(order.getRecords().get(i).getPortion()) != 0) {//正常输出的
if (order.getRecords().get(i).getIsForOther() != 0) {//代点餐的
System.out.println(order.getRecords().get(i).getOrderNum() + " table " + (whichTable - 1) + " pay for table " + order.getRecords().get(i).getIsForOther() + " " + order.getRecords().get(i).getD().getPrice(order.getRecords().get(i).getPortion()) * order.getRecords().get(i).getNum());
} else {
if (order.getRecords().get(i).getOrderNum() == 1) {
System.out.println("table " + whichTable + ": ");
countTable.add(count);
count = 0;
whichTable++;
}
System.out.print(order.getRecords().get(i).getOrderNum());
System.out.print(" " + order.getRecords().get(i).getD().getName() + " ");
System.out.println(order.getRecords().get(i).getD().getPrice(order.getRecords().get(i).getPortion()) * order.getRecords().get(i).getNum());
}
count += order.getRecords().get(i).getD().getPrice(order.getRecords().get(i).getPortion()) * order.getRecords().get(i).getNum();
} else {//delete不存在的
System.out.println(order.getRecords().get(i).getD().getName() + " does not exist");
order.getRecords().get(i).setError(true);
}
}
countTable.add(count);
for (int i = 0; i < whichTable - 1; i++) {
if (tableDiscount.get(i) < 0.0) {
System.out.println("table " + (i + 1) + " out of opening hours");
continue;
}
System.out.println("table " + (i + 1) + ": " + (int) ((countTable.get(i + 1) - Order.getRefund().get(i+1)) * tableDiscount.get(i) + 0.5));
}
}
public static double discount(String[] tableMessages){//判断折扣
LocalDateTime theTime = LocalDateTime.of(Integer.parseInt(tableMessages[2]), Integer.parseInt(tableMessages[3]), Integer.parseInt(tableMessages[4]), Integer.parseInt(tableMessages[5]), Integer.parseInt(tableMessages[6]), Integer.parseInt(tableMessages[7]));//存时间
int whichDay = theTime.getDayOfWeek().getValue();//星期几
if (whichDay >= 1 && whichDay <= 5) {//不在周末
if (Integer.parseInt(tableMessages[5]) >= 17 && Integer.parseInt(tableMessages[5]) < 20 || Integer.parseInt(tableMessages[5]) == 20 && Integer.parseInt(tableMessages[6]) <= 30) {
return 0.8;
} else if (Integer.parseInt(tableMessages[5]) > 10 && Integer.parseInt(tableMessages[5]) < 14 || Integer.parseInt(tableMessages[5]) == 10 && Integer.parseInt(tableMessages[6]) >= 30 || Integer.parseInt(tableMessages[5]) == 14 && Integer.parseInt(tableMessages[6]) <= 30) {
return 0.6;
} else {//不在时间内
return -1.0;
}
} else {//在周末
if (Integer.parseInt(tableMessages[5]) > 9 && Integer.parseInt(tableMessages[5]) < 21 || Integer.parseInt(tableMessages[5]) == 9 && Integer.parseInt(tableMessages[6]) >= 30) {
return 1.0;
} else {
return -1.0;
}
}
}
}
相关复杂度解析反思
写代码时过于随意,对的程序的整体的把握不足,没有做好前期的准备,许多的东西写一点是一点,需提前做好设计准备
类图展示:
5-4 正则表达式训练-学号校验
先读题并简单分析,列出任务:
- 找出需要校验的八位号码
- 1、2位:入学年份后两位,例如20年
- 3、4位:学院代码,软件学院代码为20
- 5位:方向代码,例如1为软件工程,7为物联网
- 6位:班级序号
- 7、8位:学号(序号)
对正则表达式的基本训练,完整代码如下:
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String id = scan.nextLine();
//加个注释,在正则表达式中用或判断多种情况
if(id.matches("[2][0-][2][0]([1][1-7]|[6][1]|[7][123]|[8][12])([1-3][0-9]|40|0[1-9])")){
System.out.println("正确");
}else{
System.out.println("错误");
}
}
}
5-5 日期问题面向对象设计(聚合一)
先读题并简单分析,列出任务:
- 求下n天
- 求前n天
- 求两个日期相差的天数
- 并按图设计类与类之间的关系
完整代码如下:
import java.util.*;
class Year{
private int value;
public Year() {//构造方法
}
public Year(int value) {//带参构造方法
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public boolean isLeapYear(){//判断是否是闰年
if( (value%4 == 0 && value%100 != 0) || value%400==0 ) {
return true;
}
return false;
}
public boolean validate(){//校验数据合法性
if(this.value<1900||this.value>2050){
return false;
}
return true;
}
public void yearIncrement(){//年份加1
value++;
}
public void yearReduction(){//年份减一
value--;
}
}
class Month {
private int value;
private Year year;
public Month() {//构造方法
}
public Month(int yearValue, int monthValue) {//带参构造方法
this.value = monthValue;
year = new Year(yearValue);
}
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;
}
public void resetMin() {//月份复位
value = 1;
}
public void resetMax() {//月份最大
value = 12;
}
public boolean validate() {//校验数据合法性
if (value <= 0 || value > 12) {
return false;
}
return true;
}
public void monthIncrement(){//月份加一
value++;
if(value>12){
resetMin();
year.yearIncrement();
}
}
public void monthReduction(){//月份减一
value--;
if(value<=0){
resetMax();
year.yearReduction();
}
}
}
class Day {
private int value;
private Month month;
private int[] mon_maxnum = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
public Day() {//构造方法
}
public Day(int yearValue, int monthValue,int dayValue) {//带参构造方法
this.value = dayValue;
month = new Month(yearValue,monthValue);
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Month getMonth() {
return month;
}
public void setMonth(Month month) {
this.month = month;
}
public void resetMin() {//天数复位
value = 1;
}
public void resetMax() {//设置天份最大
value = mon_maxnum[month.getValue()-1];
}
public boolean validate() {//校验数据合法性
if (value <= 0 || value > mon_maxnum[month.getValue()-1]) {
return false;
}
return true;
}
public void dayIncrement(){//天数加一
value++;
if(month.getYear().isLeapYear()){//判断闰年
mon_maxnum[1]=29;
}else{
mon_maxnum[1]=28;
}
if(value>mon_maxnum[month.getValue()-1]){
resetMin();
month.monthIncrement();
}
}
public void dayReduction(){//月份减一
value--;
if(month.getYear().isLeapYear()){//判断闰年
mon_maxnum[1]=29;
}else{
mon_maxnum[1]=28;
}
if(value<=0){
month.monthReduction();
resetMax();
}
}
}
class DateUtil{
private Day day;
public DateUtil() {//构造方法
}
public DateUtil(int y, int m,int d) {//带参构造方法
day = new Day(y,m,d);
}
public Day getDay() {
return day;
}
public void setDay(Day day) {
this.day = day;
}
public boolean checkInputValidate() {//校验数据合法性
if ( day.getMonth().getYear().validate()&& day.getMonth().validate() &&day.validate() ) {
return true;
}
return false;
}
public boolean compareDates(DateUtil date){//比较两个日期大小
if(date.getDay().getMonth().getYear().getValue()>day.getMonth().getYear().getValue()//date大返回true
||date.getDay().getMonth().getYear().getValue()==day.getMonth().getYear().getValue()
&&date.getDay().getMonth().getValue()>day.getMonth().getValue()
||date.getDay().getMonth().getYear().getValue()==day.getMonth().getYear().getValue()
&&date.getDay().getMonth().getValue()==day.getMonth().getValue()
&&date.getDay().getValue()>day.getValue()){
return true;
}
return false;
}
public boolean equalTwoDates(DateUtil date){//比较两个日期是否相等
if(date.getDay().getMonth().getYear().getValue()==this.getDay().getMonth().getYear().getValue()
&&date.getDay().getMonth().getValue()==this.getDay().getMonth().getValue()
&&date.getDay().getValue()==this.getDay().getValue()){
return true;
}
return false;
}
public String showDate(){//返回日期
String str = ""+day.getMonth().getYear().getValue()+"-"+day.getMonth().getValue()+"-"+day.getValue();
return str;
}
public DateUtil getNextNDays(int n){
for(int i = 0;i < n;i++){//进行n次加一天操作
day.dayIncrement();
}
return this;
}
public DateUtil getPreviousNDays(int n){
for(int i = 0;i < n;i++){//进行n次减去一天操作
day.dayReduction();
}
return this;
}
public int getDaysofDates(DateUtil date){//返回两个日期差
int temp = 0;
if(this.equalTwoDates(date)){
return 0;
}else if(this.compareDates(date)){//如果data大
while(this.compareDates(date)){
date = date.getPreviousNDays(1);
temp++;
}
}else{//如果date小
while(date.compareDates(this)){
date = date.getNextNDays(1);
temp++;
}
}
return temp;
}
}
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
if(number==1){//下n天操作
DateUtil date = new DateUtil(scan.nextInt(),scan.nextInt(),scan.nextInt());
if(!date.checkInputValidate()){//日期错误
System.out.println("Wrong Format");
return;
}
date.getNextNDays(scan.nextInt());
System.out.println(date.showDate());
}else if(number==2){//上n天操作
DateUtil date = new DateUtil(scan.nextInt(),scan.nextInt(),scan.nextInt());
if(!date.checkInputValidate()){//日期错误
System.out.println("Wrong Format");
return;
}
date.getPreviousNDays(scan.nextInt());
System.out.println(date.showDate());
}else if(number==3){//计算天数差操作
DateUtil date = new DateUtil(scan.nextInt(),scan.nextInt(),scan.nextInt());
DateUtil newdate = new DateUtil(scan.nextInt(),scan.nextInt(),scan.nextInt());
if(!date.checkInputValidate()||!newdate.checkInputValidate()){//日期错误
System.out.println("Wrong Format");
return;
}
System.out.println(date.getDaysofDates(newdate));
}else{//错误操作
System.out.println("Wrong Format");
}
}
}
相关复杂度分析:
整体还可以
相关类图:
5-6 日期问题面向对象设计(聚合二)
先读题并简单分析,列出任务:
- 同5-5
- 并按图设计类与类之间的关系
完整代码如下:
import java.util.*;
class Year{
private int value;
public Year() {//构造方法
}
public Year(int value) {//带参构造方法
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public boolean isLeapYear(){//判断是否是闰年
if( (value%4 == 0 && value%100 != 0) || value%400==0 ) {
return true;
}
return false;
}
public boolean validate(){//校验数据合法性
if(this.value<1900||this.value>2050){
return false;
}
return true;
}
public void yearIncrement(){//年份加1
value++;
}
public void yearReduction(){//年份减一
value--;
}
}
class Month {
private int value;
public Month() {//构造方法
}
public Month(int value) {//带参构造方法
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public void resetMin() {//月份复位
value = 1;
}
public void resetMax() {//月份最大
value = 12;
}
public boolean validate() {//校验数据合法性
if (value <= 0 || value > 12) {
return false;
}
return true;
}
public void monthIncrement(){//月份加一
value++;
}
public void monthReduction(){//月份减一
value--;
}
}
class Day {
private int value;
public Day() {//构造方法
}
public Day(int value) {//带参构造方法
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public void dayIncrement(){//天数加一
value++;
}
public void dayReduction(){//月份减一
value--;
}
}
class DateUtil{
private Year year;
private Month month;
private Day day;
private int[] mon_maxnum = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
public DateUtil() {//构造方法
}
public DateUtil(int y, int m,int d) {//带参构造方法
year = new Year(y);
month = new Month(m);
day = new Day(d);
}
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;
}
public void setDayMin(){
day.setValue(1);
}
public void setDayMax(){
day.setValue(mon_maxnum[month.getValue()-1]);
}
public boolean checkInputValidate() {//校验数据合法性
if (year.getValue()<1820||year.getValue()>2020
||month.getValue()<=0||month.getValue()>12
||day.getValue()<=0||day.getValue()>mon_maxnum[month.getValue()-1]) {
return false;
}
return true;
}
public DateUtil getNextNDays(int n){
if(year.isLeapYear()){
mon_maxnum[1] = 29;
}else{
mon_maxnum[1] = 28;
}
for(int i = 0;i < n;i++){//进行n次加一天操作
year.isLeapYear();
day.dayIncrement();
if(day.getValue()>mon_maxnum[month.getValue()-1]){
day.setValue(1);
month.monthIncrement();
if(month.getValue()>12){
month.resetMin();
year.yearIncrement();
if(year.isLeapYear()){
mon_maxnum[1] = 29;
}else{
mon_maxnum[1] = 28;
}
}
}
}
return this;
}
public DateUtil getPreviousNDays(int n){
if(year.isLeapYear()){
mon_maxnum[1] = 29;
}else{
mon_maxnum[1] = 28;
}
for(int i = 0;i < n;i++){//进行n次减去一天操作
day.dayReduction();
if(day.getValue()<=0){
month.monthReduction();
if(month.getValue()<=0){
month.resetMax();
year.yearReduction();
if(year.isLeapYear()){
mon_maxnum[1] = 29;
}else{
mon_maxnum[1] = 28;
}
}
day.setValue(mon_maxnum[month.getValue()-1]);
}
}
return this;
}
public boolean compareDates(DateUtil date){//比较两个日期大小
if(date.getYear().getValue()>year.getValue()//date大返回true
||date.getYear().getValue()==year.getValue()
&&date.getMonth().getValue()>month.getValue()
||date.getYear().getValue()==year.getValue()
&&date.getMonth().getValue()==month.getValue()
&&date.getDay().getValue()>day.getValue()){
return true;
}
return false;
}
public boolean equalTwoDates(DateUtil date){//比较两个日期是否相等
if(date.getYear().getValue()==year.getValue()
&&date.getMonth().getValue()==month.getValue()
&&date.getDay().getValue()==day.getValue()){
return true;
}
return false;
}
public int getDaysofDates(DateUtil date){//返回两个日期差
int temp = 0;
if(this.equalTwoDates(date)){
return 0;
}else if(this.compareDates(date)){//如果data大
while(this.compareDates(date)){
date = date.getPreviousNDays(1);
temp++;
}
}else{//如果date小
while(date.compareDates(this)){
date = date.getNextNDays(1);
temp++;
}
}
return temp;
}
public String showDate(){//返回日期
String str = ""+year.getValue()+"-"+month.getValue()+"-"+day.getValue();
return str;
}
}
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
if(number==1){//下n天操作
int year = scan.nextInt();
int month = scan.nextInt();
int day = scan.nextInt();
int next = scan.nextInt();
DateUtil initDate = new DateUtil(year,month,day);
DateUtil date = new DateUtil(year,month,day);
if(!date.checkInputValidate()){//日期错误
System.out.println("Wrong Format");
return;
}
date.getNextNDays(next);
System.out.println(initDate.showDate()+" next " +next+ " days is:"+date.showDate());
}else if(number==2){//上n天操作
int year = scan.nextInt();
int month = scan.nextInt();
int day = scan.nextInt();
int last = scan.nextInt();
DateUtil initDate = new DateUtil(year,month,day);
DateUtil date = new DateUtil(year,month,day);
if(!date.checkInputValidate()){//日期错误
System.out.println("Wrong Format");
return;
}
date.getPreviousNDays(last);
System.out.println(initDate.showDate()+" previous " +last+ " days is:"+date.showDate());
}else if(number==3){//计算天数差操作
int year = scan.nextInt();
int month = scan.nextInt();
int day = scan.nextInt();
int year2 = scan.nextInt();
int month2 = scan.nextInt();
int day2 = scan.nextInt();
DateUtil date = new DateUtil(year,month,day);
DateUtil newdate = new DateUtil(year2,month2,day2);
if(!date.checkInputValidate()||!newdate.checkInputValidate()){//日期错误
System.out.println("Wrong Format");
return;
}
System.out.println("The days between "+date.showDate()+" and " +newdate.showDate()+ " are:"+date.getDaysofDates(newdate));
}else{//错误操作
System.out.println("Wrong Format");
}
}
}
相关复杂度分析:
整体还行
相关类图:
对比5-5和5-6的区别:
在我看来5-5的聚合一类之间的控制的程度更高day,month,year被紧紧关联,但是可以更好的将方法写入对应的类中
5-6的优点是更加简便,方便调用类中的方法,耦合性更低
6-4 ATM机类结构设计(一)
本题目标明确按照题目编写以下方法:
- 存款、取款功能
- 查询余额功能输入数据格式
- 输入错误处理
先对账户进行初始化,为方便写了个control类,将方法写入其中
public static void init(){
//指针指向了同一个card//
ArrayList<Card> card1 = new ArrayList<Card>();
card1.add(new Card("6217000010041315709"));
card1.add(new Card("6217000010041315715"));
YangGuo = new User("杨过","3217000010041315709",10000.00,"中国建设银行",card1);
ArrayList<Card> card2 = new ArrayList<Card>();
card2.add(new Card("6217000010041315718"));
YangGuo.getAccount().add(new Account("3217000010041315715",10000.00,new Bank("中国建设银行"),card2));
ArrayList<Card> card3 = new ArrayList<Card>();
card3.add(new Card("6217000010051320007"));
GuoJing = new User("郭靖","3217000010051320007",10000.00,"中国建设银行",card3);
ArrayList<Card> card4 = new ArrayList<Card>();
card4.add(new Card("6222081502001312389"));
ZhangWuJi = new User("张无忌","3222081502001312389",10000.00,"中国工商银行",card4);
ArrayList<Card> card5 = new ArrayList<Card>();
card5.add(new Card("6222081502001312390"));
ZhangWuJi.getAccount().add(new Account("3222081502001312390",10000.00,new Bank("中国工商银行"),card5));
ArrayList<Card> card6 = new ArrayList<Card>();
card6.add(new Card("6222081502001312399"));
card6.add(new Card("6222081502001312400"));
ZhangWuJi.getAccount().add(new Account("3222081502001312399",10000.00,new Bank("中国工商银行"),card6));
ArrayList<Card> card7 = new ArrayList<Card>();
card7.add(new Card("6222081502051320785"));
WeiXiaoBao = new User("韦小宝 ","3222081502051320785",10000.00,"中国工商银行",card7);
ArrayList<Card> card8 = new ArrayList<Card>();
card8.add(new Card("6222081502051320786"));
WeiXiaoBao.getAccount().add(new Account("3222081502051320786",10000.00,new Bank("中国工商银行"),card8));
}
重点是对账户进行查找,该方法如果找到用户则进行相应操作,并返回当前余额
public static double returnMoney(User user,String[] allData){//如果找到对应卡号返回当前余额
for (int i = 0; i < user.getAccount().size(); i++) {//多个账户
for (int j = 0; j < user.getAccount().get(i).getCard().size(); j++) {//多个卡号
if (allData[0].equals(user.getAccount().get(i).getCard().get(j).getCardId())) {
if(allData[1].equals("88888888")){
checkATM(user.getAccount().get(i),allData);
if(user.getAccount().get(i).getMoney()>Double.parseDouble(allData[3])){
user.getAccount().get(i).setMoney(user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3]));
return user.getAccount().get(i).getMoney();
}else{//金额不足
System.out.println("Sorry,your account balance is insufficient.");
System.exit(0);
}
}else{//密码错误
System.out.println("Sorry,your password is wrong.");
System.exit(0);
}
}
}
}
return 0;//没找到
完整代码如下:
import java.util.*;
class ChinaUnionPay{
private ArrayList<Bank> bank;
}
class Bank {
private String bankName;//银行名
private ATM ATMs[];
public Bank(String bankName) {
this.bankName = bankName;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public static boolean isRightBank(String bankName, String Id){
if(bankName.equals("中国建设银行")){
if(Id.matches("[0][01234]")){
return true;
}
}
if(bankName.equals("中国工商银行")){
if(Id.matches("[0][056]")){
return true;
}
}
return false;
}
}
class Account{
private String accountId;
private double money;
private Bank bank;//所属银行
private ArrayList<Card> card;
public Account(String accountId, double money, Bank bank, ArrayList<Card> card) {
this.accountId = accountId;
this.money = money;
this.bank = bank;
this.card = card;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public Bank getBank() {
return bank;
}
public void setBank(Bank bank) {
this.bank = bank;
}
public ArrayList<Card> getCard() {
return card;
}
public void setCard(ArrayList<Card> card) {
this.card = card;
}
public static double returnMoney(User user,String[] allData){//如果找到对应卡号返回当前余额
for (int i = 0; i < user.getAccount().size(); i++) {//多个账户
for (int j = 0; j < user.getAccount().get(i).getCard().size(); j++) {//多个卡号
if (allData[0].equals(user.getAccount().get(i).getCard().get(j).getCardId())) {
if(allData[1].equals("88888888")){
checkATM(user.getAccount().get(i),allData);
if(user.getAccount().get(i).getMoney()>Double.parseDouble(allData[3])){
user.getAccount().get(i).setMoney(user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3]));
return user.getAccount().get(i).getMoney();
}else{//金额不足
System.out.println("Sorry,your account balance is insufficient.");
System.exit(0);
}
}else{//密码错误
System.out.println("Sorry,your password is wrong.");
System.exit(0);
}
}
}
}
return 0;//没找到
}
public static void checkATM(Account account,String[] allData){
if(!ATM.isRightId(allData[2])){
System.out.println("Sorry,the ATM's id is wrong.");
System.exit(0);
}
if(!Bank.isRightBank(account.getBank().getBankName(),allData[2])){
System.out.println("Sorry,cross-bank withdrawal is not supported.");
System.exit(0);
}
}
}
class Card{
private String cardId;
public Card(String cardId) {
this.cardId = cardId;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
}
class ATM{
private int ATMId;
public ATM(int ATMId) {
this.ATMId = ATMId;
}
public int getATMId() {
return ATMId;
}
public void setATMId(int ATMId) {
this.ATMId = ATMId;
}
public static boolean isRightId(String Id) {
if(Id.matches("[0][0123456]")){
return true;
}
return false;
}
}
class User{
private String userName;
private ArrayList<Account> account = new ArrayList<Account>();
public User() {
}
public User(String userName,String accountId,double money,String bank,ArrayList<Card> card) {
this.userName = userName;
Account temp = new Account(accountId,money,new Bank(bank),card);
this.account.add(temp);
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public ArrayList<Account> getAccount() {
return account;
}
public void setAccount(ArrayList<Account> account) {
this.account = account;
}
}
class Control{
static User YangGuo;
static User GuoJing;
static User ZhangWuJi;
static User WeiXiaoBao;
public static void init(){
//指针指向了同一个card//
ArrayList<Card> card1 = new ArrayList<Card>();
card1.add(new Card("6217000010041315709"));
card1.add(new Card("6217000010041315715"));
YangGuo = new User("杨过","3217000010041315709",10000.00,"中国建设银行",card1);
ArrayList<Card> card2 = new ArrayList<Card>();
card2.add(new Card("6217000010041315718"));
YangGuo.getAccount().add(new Account("3217000010041315715",10000.00,new Bank("中国建设银行"),card2));
ArrayList<Card> card3 = new ArrayList<Card>();
card3.add(new Card("6217000010051320007"));
GuoJing = new User("郭靖","3217000010051320007",10000.00,"中国建设银行",card3);
ArrayList<Card> card4 = new ArrayList<Card>();
card4.add(new Card("6222081502001312389"));
ZhangWuJi = new User("张无忌","3222081502001312389",10000.00,"中国工商银行",card4);
ArrayList<Card> card5 = new ArrayList<Card>();
card5.add(new Card("6222081502001312390"));
ZhangWuJi.getAccount().add(new Account("3222081502001312390",10000.00,new Bank("中国工商银行"),card5));
ArrayList<Card> card6 = new ArrayList<Card>();
card6.add(new Card("6222081502001312399"));
card6.add(new Card("6222081502001312400"));
ZhangWuJi.getAccount().add(new Account("3222081502001312399",10000.00,new Bank("中国工商银行"),card6));
ArrayList<Card> card7 = new ArrayList<Card>();
card7.add(new Card("6222081502051320785"));
WeiXiaoBao = new User("韦小宝 ","3222081502051320785",10000.00,"中国工商银行",card7);
ArrayList<Card> card8 = new ArrayList<Card>();
card8.add(new Card("6222081502051320786"));
WeiXiaoBao.getAccount().add(new Account("3222081502051320786",10000.00,new Bank("中国工商银行"),card8));
}
public static void changeDeposit(String[] allData) {
double money = 0;//当前余额
if((money+= Account.returnMoney(YangGuo,allData))!=0){//判断是否为杨过的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){//判断存取款
System.out.printf("杨过在中国建设银行的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("杨过在中国建设银行的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
} else if ((money+= Account.returnMoney(GuoJing,allData))!=0) {//判断是否为郭靖的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){
System.out.printf("郭靖在中国建设银行的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("郭靖在中国建设银行的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
}else if ((money+= Account.returnMoney(ZhangWuJi,allData))!=0) {//判断是否为张无忌的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){
System.out.printf("张无忌在中国工商银行的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("张无忌在中国工商银行的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
}else if ((money+= Account.returnMoney(WeiXiaoBao,allData))!=0) {//判断是否为韦小宝的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){
System.out.printf("韦小宝在中国工商银行的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("韦小宝在中国工商银行的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
}else{//错误
System.out.println("Sorry,this card does not exist.");
}
}
public static boolean isDeposit(double money){//判断是否是存款
if(money>0){
return true;
}else{
return false;
}
}
public static void showMoney(String[] alldata){//显示存款
double money = 0;//当前余额
String[] allData = new String[]{alldata[0],"88888888","00","0"};
if((money+=Account.returnMoney(YangGuo,allData))!=0){//判断是否为杨过的某张账户
System.out.printf("¥%.2f\n",money);
} else if ((money+= Account.returnMoney(GuoJing,allData))!=0) {//判断是否为郭靖的某张账户
System.out.printf("¥%.2f\n",money);
}else if ((money+= Account.returnMoney(ZhangWuJi,allData))!=0) {//判断是否为张无忌的某张账户
System.out.printf("¥%.2f\n",money);
}else if ((money+= Account.returnMoney(WeiXiaoBao,allData))!=0) {//判断是否为韦小宝的某张账户
System.out.printf("¥%.2f\n",money);
}else{//错误
System.out.println("Sorry,this card does not exist.");
}
}
}
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Control.init();
String data = scan.nextLine();
while(!data.equals("#")){
String[] allData = data.split("\\s+");
if(allData.length == 4){
Control.changeDeposit(allData);
} else if (allData.length == 1) {
Control.showMoney(allData);
}else{
return;
}
data = scan.nextLine();
}
}
}
相关复杂度分析及反思:
反思:没有注重单一职责,将责任分配过乱 如
public static double returnMoney(User user,String[] allData){//如果找到对应卡号返回当前余额
for (int i = 0; i < user.getAccount().size(); i++) {//多个账户
for (int j = 0; j < user.getAccount().get(i).getCard().size(); j++) {//多个卡号
if (allData[0].equals(user.getAccount().get(i).getCard().get(j).getCardId())) {
if(allData[1].equals("88888888")){
checkATM(user.getAccount().get(i),allData);
if(user.getAccount().get(i).getMoney()>Double.parseDouble(allData[3])){
user.getAccount().get(i).setMoney(user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3]));
return user.getAccount().get(i).getMoney();
}else{//金额不足
System.out.println("Sorry,your account balance is insufficient.");
System.exit(0);
}
}else{//密码错误
System.out.println("Sorry,your password is wrong.");
System.exit(0);
}
}
}
}
return 0;//没找到
类图展示:
6-5 ATM机类结构设计(二)
本题目标明确按照题目编写以下方法:
- 存款、取款功能
- 查询余额功能输入数据格式
- 输入错误处理
- 跨行业务手续费收取
- 透支取款
在原来的6-4中加了一些新的操作
是否跨行判断
public static boolean isRightBank(String bankName, String Id){
if(bankName.equals("中国建设银行")){
if(Id.matches("[0][1234]")){
return true;
}
}
if(bankName.equals("中国工商银行")){
if(Id.matches("[0][56]")){
return true;
}
}
if(bankName.equals("中国农业银行")){
if(Id.matches("([0][789])|([1][01])")){
return true;
}
}
return false;
}
手续费计算
public static Double premium(String bankName,String ATMId){//计算跨行手续费
if(!bankName.equals("中国建设银行")) {
if (ATMId.matches("[0][1234]")) {
return 1.02;
}
}
if(!bankName.equals("中国工商银行")) {
if (ATMId.matches("[0][56]")) {
return 1.03;
}
}
if(!bankName.equals("中国农业银行")) {
if (ATMId.matches("([0][789])|([1][01])")) {
return 1.04;
}
}
return 1.0;
}
完整代码如下:
import java.util.*;
class ChinaUnionPay{
private ArrayList<Bank> bank;
}
class Bank {
private String bankName;//银行名
private ATM ATMs[];
public Bank(String bankName) {
this.bankName = bankName;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public static boolean isRightBank(String bankName, String Id){
if(bankName.equals("中国建设银行")){
if(Id.matches("[0][1234]")){
return true;
}
}
if(bankName.equals("中国工商银行")){
if(Id.matches("[0][56]")){
return true;
}
}
if(bankName.equals("中国农业银行")){
if(Id.matches("([0][789])|([1][01])")){
return true;
}
}
return false;
}
public static Double premium(String bankName,String ATMId){//计算跨行手续费
if(!bankName.equals("中国建设银行")) {
if (ATMId.matches("[0][1234]")) {
return 1.02;
}
}
if(!bankName.equals("中国工商银行")) {
if (ATMId.matches("[0][56]")) {
return 1.03;
}
}
if(!bankName.equals("中国农业银行")) {
if (ATMId.matches("([0][789])|([1][01])")) {
return 1.04;
}
}
return 1.0;
}
}
class Account{
private String accountId;//账户号
private double money;//余额
private Bank bank;//所属银行
private ArrayList<Card> card;//下属几个卡号
private String type;//类型
public Account(String accountId, double money, Bank bank, ArrayList<Card> card,String type) {
this.accountId = accountId;
this.money = money;
this.bank = bank;
this.card = card;
this.type = type;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public Bank getBank() {
return bank;
}
public void setBank(Bank bank) {
this.bank = bank;
}
public ArrayList<Card> getCard() {
return card;
}
public void setCard(ArrayList<Card> card) {
this.card = card;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public static double returnMoney(User user, String[] allData){//如果找到对应卡号返回当前余额
for (int i = 0; i < user.getAccount().size(); i++) {//多个账户
for (int j = 0; j < user.getAccount().get(i).getCard().size(); j++) {//多个卡号
if (allData[0].equals(user.getAccount().get(i).getCard().get(j).getCardId())) {
if(allData[1].equals("88888888")){//密码正确
checkATM(user.getAccount().get(i),allData);//检查ATM是否正常
double times = 1.0;
if (Double.parseDouble(allData[3]) == 0) {//直接返回
return user.getAccount().get(i).getMoney();
}
if(Double.parseDouble(allData[3])>0){//如果是取款
times = Bank.premium(user.getAccount().get(i).getBank().getBankName(),allData[2]);//计算手续费倍数
}
if(user.getAccount().get(i).getMoney()>Double.parseDouble(allData[3])){//钱够
user.getAccount().get(i).setMoney(user.getAccount().get(i).getMoney()-(Double.parseDouble(allData[3]))*times);
return user.getAccount().get(i).getMoney();
}else if(user.getAccount().get(i).getType().equals("贷记账号")&&user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3])<50000){//或为贷记卡够贷50000
if(user.getAccount().get(i).getMoney()>0){//如果没欠钱
if((user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3])*1.05)-Double.parseDouble(allData[3])*(times-1)>-50000){
user.getAccount().get(i).setMoney((user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3]))*1.05-Double.parseDouble(allData[3])*(times-1));
return user.getAccount().get(i).getMoney();
}else{//金额不足
System.out.println("Sorry,your account balance is insufficient.");
System.exit(0);
}
}else{//如果本来就欠了钱
if((user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3])*1.05)-Double.parseDouble(allData[3])*(times-1)>-50000){
user.getAccount().get(i).setMoney((user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3])*1.05)-Double.parseDouble(allData[3])*(times-1));
return user.getAccount().get(i).getMoney();
}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{//密码错误
System.out.println("Sorry,your password is wrong.");
System.exit(0);
}
}
}
}
return 0;//没找到
}
public static void checkATM(Account account,String[] allData){
if(!ATM.isRightId(allData[2])){
System.out.println("Sorry,the ATM's id is wrong.");
System.exit(0);
}
}
}
class Card{
private String cardId;
public Card(String cardId) {
this.cardId = cardId;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
}
class ATM {
private int ATMId;
public ATM(int ATMId) {
this.ATMId = ATMId;
}
public int getATMId() {
return ATMId;
}
public void setATMId(int ATMId) {
this.ATMId = ATMId;
}
public static boolean isRightId(String Id) {
if (Id.matches("([0][0123456789])|([1][01])")) {
return true;
}
return false;
}
public static String BelongsBank(String Id) {
if (Id.matches("[0][1234]")) {
return "中国建设银行";
}
if (Id.matches("[0][56]")) {
return "中国工商银行";
}
if (Id.matches("([0][789])|([1][01])")) {
return "中国农业银行";
}
return null;
}
}
class User{
private String userName;
private ArrayList<Account> account = new ArrayList<Account>();
public User() {
}
public User(String userName,String accountId,double money,String bank,ArrayList<Card> card,String type) {
this.userName = userName;
Account temp = new Account(accountId,money,new Bank(bank),card,type);
this.account.add(temp);
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public ArrayList<Account> getAccount() {
return account;
}
public void setAccount(ArrayList<Account> account) {
this.account = account;
}
}
class Control{
static User YangGuo;
static User GuoJing;
static User ZhangWuJi;
static User WeiXiaoBao;
static User ZhangSanFeng;
static User LingHuChong;
static User QiaoFeng;
static User HongQiGong;
public static void init(){
//指针指向了同一个card//
ArrayList<Card> card1 = new ArrayList<Card>();
card1.add(new Card("6217000010041315709"));
card1.add(new Card("6217000010041315715"));
YangGuo = new User("杨过","3217000010041315709",10000.00,"中国建设银行",card1,"借记账号");
ArrayList<Card> card2 = new ArrayList<Card>();
card2.add(new Card("6217000010041315718"));
YangGuo.getAccount().add(new Account("3217000010041315715",10000.00,new Bank("中国建设银行"),card2,"借记账号"));
ArrayList<Card> card3 = new ArrayList<Card>();
card3.add(new Card("6217000010051320007"));
GuoJing = new User("郭靖","3217000010051320007",10000.00,"中国建设银行",card3,"借记账号");
ArrayList<Card> card4 = new ArrayList<Card>();
card4.add(new Card("6222081502001312389"));
ZhangWuJi = new User("张无忌","3222081502001312389",10000.00,"中国工商银行",card4,"借记账号");
ArrayList<Card> card5 = new ArrayList<Card>();
card5.add(new Card("6222081502001312390"));
ZhangWuJi.getAccount().add(new Account("3222081502001312390",10000.00,new Bank("中国工商银行"),card5,"借记账号"));
ArrayList<Card> card6 = new ArrayList<Card>();
card6.add(new Card("6222081502001312399"));
card6.add(new Card("6222081502001312400"));
ZhangWuJi.getAccount().add(new Account("3222081502001312399",10000.00,new Bank("中国工商银行"),card6,"借记账号"));
ArrayList<Card> card7 = new ArrayList<Card>();
card7.add(new Card("6222081502051320785"));
WeiXiaoBao = new User("韦小宝 ","3222081502051320785",10000.00,"中国工商银行",card7,"借记账号");
ArrayList<Card> card8 = new ArrayList<Card>();
card8.add(new Card("6222081502051320786"));
WeiXiaoBao.getAccount().add(new Account("3222081502051320786",10000.00,new Bank("中国工商银行"),card8,"借记账号"));
ArrayList<Card> card9 = new ArrayList<Card>();
card9.add(new Card("6640000010045442002"));
card9.add(new Card("6640000010045442003"));
ZhangSanFeng = new User("张三丰 ","3640000010045442002",10000.00,"中国建设银行",card9,"贷记账号");
ArrayList<Card> card10 = new ArrayList<Card>();
card10.add(new Card("6640000010045441009"));
LingHuChong = new User("令狐冲","3640000010045441009",10000.00,"中国工商银行",card10,"贷记账号");
ArrayList<Card> card11 = new ArrayList<Card>();
card11.add(new Card("6630000010033431001"));
QiaoFeng= new User("乔峰","3630000010033431001",10000.00,"中国农业银行",card11,"贷记账号");
ArrayList<Card> card12 = new ArrayList<Card>();
card12.add(new Card("6630000010033431008"));
HongQiGong= new User("洪七公","3630000010033431008",10000.00,"中国农业银行",card12,"贷记账号");
}
public static void changeDeposit(String[] allData) {
double money = 0;//当前余额
String useBank = ATM.BelongsBank(allData[2]);//所用银行
if((money+= Account.returnMoney(YangGuo,allData))!=0){//判断是否为杨过的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){//判断存取款
System.out.printf("业务:取款 杨过在"+useBank+"的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("杨过在"+useBank+"的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
} else if ((money+= Account.returnMoney(GuoJing,allData))!=0) {//判断是否为郭靖的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){
System.out.printf("业务:取款 郭靖在"+useBank+"的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("郭靖在"+useBank+"的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
}else if ((money+= Account.returnMoney(ZhangWuJi,allData))!=0) {//判断是否为张无忌的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){
System.out.printf("业务:取款 张无忌在"+useBank+"的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("张无忌在"+useBank+"的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
}else if ((money+= Account.returnMoney(WeiXiaoBao,allData))!=0) {//判断是否为韦小宝的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){
System.out.printf("业务:取款 韦小宝在"+useBank+"的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("韦小宝在"+useBank+"的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
}else if ((money+= Account.returnMoney(ZhangSanFeng,allData))!=0) {//判断是否为张三丰的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){
System.out.printf("业务:取款 张三丰在"+useBank+"的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("张三丰在"+useBank+"的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
}else if ((money+= Account.returnMoney(LingHuChong,allData))!=0) {//判断是否为令狐冲的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){
System.out.printf("业务:取款 令狐冲在"+useBank+"的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("令狐冲在"+useBank+"的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
}else if ((money+= Account.returnMoney(QiaoFeng,allData))!=0) {//判断是否为乔峰的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){
System.out.printf("业务:取款 乔峰在"+useBank+"的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("乔峰在"+useBank+"的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
}else if ((money+= Account.returnMoney(HongQiGong,allData))!=0) {//判断是否为洪七公的某张账户
if(isDeposit(Double.parseDouble(allData[3]))){
System.out.printf("业务:取款 洪七公在"+useBank+"的"+allData[2]+"号ATM机上取款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}else{
System.out.printf("洪七公在"+useBank+"的"+allData[2]+"号ATM机上存款¥%.2f\n",Math.abs(Double.parseDouble(allData[3])));
}
System.out.printf("当前余额为¥%.2f\n",money);
}else{//错误
System.out.println("Sorry,this card does not exist.");
System.exit(0);
}
}
public static boolean isDeposit(double money){//判断是否是存款
if(money>0){
return true;
}else{
return false;
}
}
public static void showMoney(String[] alldata){//显示存款
double money = 0;//当前余额
String[] allData = new String[]{alldata[0],"88888888","00","0"};
if((money+=Account.returnMoney(YangGuo,allData))!=0){//判断是否为杨过的某张账户
System.out.printf("业务:查询余额 ¥%.2f\n",money);
} else if ((money+= Account.returnMoney(GuoJing,allData))!=0) {//判断是否为郭靖的某张账户
System.out.printf("业务:查询余额 ¥%.2f\n",money);
}else if ((money+= Account.returnMoney(ZhangWuJi,allData))!=0) {//判断是否为张无忌的某张账户
System.out.printf("业务:查询余额 ¥%.2f\n",money);
}else if ((money+= Account.returnMoney(WeiXiaoBao,allData))!=0) {//判断是否为韦小宝的某张账户
System.out.printf("业务:查询余额 ¥%.2f\n",money);
}else if ((money+= Account.returnMoney(ZhangSanFeng,allData))!=0) {//判断是否为韦小宝的某张账户
System.out.printf("业务:查询余额 ¥%.2f\n",money);
}else if ((money+= Account.returnMoney(LingHuChong,allData))!=0) {//判断是否为韦小宝的某张账户
System.out.printf("业务:查询余额 ¥%.2f\n",money);
}else if ((money+= Account.returnMoney(QiaoFeng,allData))!=0) {//判断是否为韦小宝的某张账户
System.out.printf("业务:查询余额 ¥%.2f\n",money);
}else if ((money+= Account.returnMoney(HongQiGong,allData))!=0) {//判断是否为韦小宝的某张账户
System.out.printf("业务:查询余额 ¥%.2f\n",money);
}else{//错误
System.out.println("Sorry,this card does not exist.");
System.exit(0);
}
}
}
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Control.init();
String data = scan.nextLine();
while(!data.equals("#")){
String[] allData = data.split("\\s+");
if(allData.length == 4){
Control.changeDeposit(allData);
} else if (allData.length == 1) {
Control.showMoney(allData);
}else{
return;
}
data = scan.nextLine();
}
}
}
相关复杂度分析及反思:
反思:对这次自己写的这个代码挺不满意,在解决问题时往往只考虑了去解决问题,没有关注可读性和复用性,为了简便许多东西和判断被写在了一起如
查找和更改余额操作写一起
public static double returnMoney(User user, String[] allData){//如果找到对应卡号返回当前余额
for (int i = 0; i < user.getAccount().size(); i++) {//多个账户
for (int j = 0; j < user.getAccount().get(i).getCard().size(); j++) {//多个卡号
if (allData[0].equals(user.getAccount().get(i).getCard().get(j).getCardId())) {
if(allData[1].equals("88888888")){//密码正确
checkATM(user.getAccount().get(i),allData);//检查ATM是否正常
double times = 1.0;
if (Double.parseDouble(allData[3]) == 0) {//直接返回
return user.getAccount().get(i).getMoney();
}
if(Double.parseDouble(allData[3])>0){//如果是取款
times = Bank.premium(user.getAccount().get(i).getBank().getBankName(),allData[2]);//计算手续费倍数
}
if(user.getAccount().get(i).getMoney()>Double.parseDouble(allData[3])){//钱够
user.getAccount().get(i).setMoney(user.getAccount().get(i).getMoney()-(Double.parseDouble(allData[3]))*times);
return user.getAccount().get(i).getMoney();
}else if(user.getAccount().get(i).getType().equals("贷记账号")&&user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3])<50000){//或为贷记卡够贷50000
if(user.getAccount().get(i).getMoney()>0){//如果没欠钱
if((user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3])*1.05)-Double.parseDouble(allData[3])*(times-1)>-50000){
user.getAccount().get(i).setMoney((user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3]))*1.05-Double.parseDouble(allData[3])*(times-1));
return user.getAccount().get(i).getMoney();
}else{//金额不足
System.out.println("Sorry,your account balance is insufficient.");
System.exit(0);
}
}else{//如果本来就欠了钱
if((user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3])*1.05)-Double.parseDouble(allData[3])*(times-1)>-50000){
user.getAccount().get(i).setMoney((user.getAccount().get(i).getMoney()-Double.parseDouble(allData[3])*1.05)-Double.parseDouble(allData[3])*(times-1));
return user.getAccount().get(i).getMoney();
}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{//密码错误
System.out.println("Sorry,your password is wrong.");
System.exit(0);
}
}
}
}
return 0;//没找到
类图展示:
采坑心得
在第六次题目集中对账户初始化时的List指向问题
ArrayList<Card> card1 = new ArrayList<Card>();
card1.add(new Card("6217000010041315709"));
card1.add(new Card("6217000010041315715"));
YangGuo = new User("杨过","3217000010041315709",10000.00,"中国建设银行",card1,"借记账号");
card1.clear();
card1.add(new Card("6217000010041315718"));
YangGuo.getAccount().add(new Account("3217000010041315715",10000.00,new Bank("中国建设银行"),card1,"借记账号"));
这样写结果两个账户的card为指向同一个List,应新建一个List
改进建议
在这次的第六次题目集中,由于其他费时的小组作业,导致本次6-4,6-5开题较晚,最后还是在结束前3分钟才完成的,对于代码的规范性很差。。
在主方法中,对代码的分块不充分,行文较乱。
在类中,方法的分工不明确,方法找不清相应的主人(类)
总结
本次3个题目集作为Java类设计的习题练习,
对类有一个深入的了解,能够简单设计多个类,合理设计出类之间的一些简单关系。