java面对对象第二次博客作业

hgxblog / 2023-04-29 / 原文

(1)前言:

三次作业将java面向对象的重要的三大技术特性,封装性、继承性与多态性在这三次作业的是重要的学习知识,三次作业知识环环相扣,每一次作业主要为下一次作业做准备,写下一次作业的时候就会发现前一次作业的重要性,前一次作业主要是为了下一次作业打下一些知识以及想法的基础,这三次的作业的知识也是很多要学习的,第一次作业主要是掌握正则表达式和初步简单的继承,第二次作业则是在第一次作业的基础上对Java的继承技术特性增加了复杂度,同时也加多态性这一技术特性,第二次作业也是有正则表达式的相关知识,进一步的巩固了正则表达式的知识内容,第三次作业在第一次和第二次的作业基础上增加了多个类的继承,以及多态和接口,对多个类的处理增加了难度,这三次作业都体现了封装这一技术特性。总的来说这仨那次作业的知识迭代关系就是层层加固,可以用初学——掌握——熟练这一知识迭代关系来表示。

(2)设计与分析:

1.题目集4的7-1:

这道题我没写出来,我在写这道Java编程作业,我花了几个小时甚至一整个晚上的时间,无法成功解决它。由于时间的压力和挫败感的崛起,我最终放弃了这个作业。

现在回想起来,我认为自己应该做出更好的反应。首先,我应该认识到这是一项困难的任务,需要更多的时间和精力来解决。我一开始可能没有给自己足够的时间来思考问题,而是迫不及待地开始编写代码。这样的行为在长期看来是不可持续的,因为无法正确处理问题可能会导致更多的时间浪费。

其次,我认为我应该尝试采用不同的方法来解决这个问题。我的错误是一遇到困难就变得沮丧和绝望,我没有想到采用其他方法,例如查看文档、寻求帮助、寻找更多的示例代码等等。如果我能够更加冷静和有条理地考虑解决方案,那么我很有可能会找到解决这个问题的方法。

最后,我认为我应该把这个问题当做一个学习的机会。作为一个软件工程学生,我经常会遇到不同的问题和挑战,但这些问题都是一个机会,让我提高自己的技能和知识。我应该对这个问题保持乐观的态度,并尽可能地从中学习。

总之,我认为这次经历教育了我一些重要的教训。我应该给自己足够的时间来解决问题,采用不同的方法,以及把问题看做一个学习的机会。我相信,通过这样的反思和改进,我可以成为一个更好的程序员。

 

2.题目集5的7-5

这个代码说实话,我已经不太记得了,但在设计这段代码的时候,由于之前已经铺垫了好多,所以写起来不是太难。

类图:

 代码分析图:

 

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = 0;
int month = 0;
int day = 0;

int choice = input.nextInt();

if (choice == 1) { // test getNextNDays method
int m = 0;
year = Integer.parseInt(input.next());
month = Integer.parseInt(input.next());
day = Integer.parseInt(input.next());

DateUtil date = new DateUtil( day,month,year );

if (!date.checkInputValidity()) {
System.out.print("Wrong Format");
System.exit(0);
}

m = input.nextInt();

if (m < 0) {
System.out.print("Wrong Format");
System.exit(0);
}

System.out.print(date.getNextNDays(m).showDate());
} else if (choice == 2) { // test getPreviousNDays method
int n = 0;
year = Integer.parseInt(input.next());
month = Integer.parseInt(input.next());
day = Integer.parseInt(input.next());

DateUtil date = new DateUtil( day,month,year );

if (!date.checkInputValidity()) {
System.out.print("Wrong Format");
System.exit(0);
}

n = input.nextInt();

if (n < 0) {
System.out.print("Wrong Format");
System.exit(0);
}

System.out.print(date.getPreviousNDays(n).showDate());
} else if (choice == 3) { //test getDaysofDates method
year = Integer.parseInt(input.next());
month = Integer.parseInt(input.next());
day = Integer.parseInt(input.next());

int anotherYear = Integer.parseInt(input.next());
int anotherMonth = Integer.parseInt(input.next());
int anotherDay = Integer.parseInt(input.next());

DateUtil fromDate = new DateUtil( day, month,year);
DateUtil toDate = new DateUtil( anotherDay, anotherMonth,anotherYear);

if (fromDate.checkInputValidity() && toDate.checkInputValidity()) {
System.out.print(fromDate.getDaysofDates(toDate));
} else {
System.out.print("Wrong Format");
System.exit(0);
}
}
else{
System.out.print("Wrong Format");
System.exit(0);
}
}
}

class DateUtil {
Day day;

public DateUtil() {
day=new Day();
}

public DateUtil(int d,int m,int y) {
day=new Day(y,m,d);
}

public Day getDay() {
return day;
}

public void setDay(Day day) {
this.day = day;
}

public boolean checkInputValidity() {
if(day.month.year.getValue()<1900||day.month.year.getValue()>2050||day.month.getValue()>12||day.month.getValue()<1||day.getValue()<1||day.getValue()>31) {
return false;
}
if(day.month.year.isLeapYear()){
if((day.month.getValue()==4||day.month.getValue()==6||day.month.getValue()==9||day.month.getValue()==11)&&day.getValue()>30)
return false;
if(day.month.getValue()==2&&day.getValue()>29)
return false;
}
else{
if((day.month.getValue()==4||day.month.getValue()==6||day.month.getValue()==9||day.month.getValue()==11)&&day.getValue()>30)
return false;
if(day.month.getValue()==2&&day.getValue()>28)
return false;
}
return true;
}
public boolean compareDates(DateUtil date) {
if (day.month.year.getValue() < date.day.month.year.getValue()) {
return true;
} else if (day.month.year.getValue() > date.day.month.year.getValue()) {
return false;
} else if (day.month.getValue() < date.day.month.getValue()) {
return true;
} else if (day.month.getValue() > date.day.month.getValue()) {
return false;
} else if (day.getValue() < date.day.getValue()) {
return true;
} else {
return false;
}
}
public boolean equalTwoDates(DateUtil date) {
return (day.month.year.getValue() == date.day.month.year.getValue() && day.month.getValue() == date.day.month.getValue() && day.getValue() == date.day.getValue());
}
public String showDate() {
return day.month.year.getValue()+"-"+day.month.getValue()+"-"+day.getValue();
}
public DateUtil getNextNDays(int n) {
while (n > 0) {
int maxDay = day.mon_maxnum[day.month.getValue()-1];
if (day.month.getValue() == 2 && day.month.year.isLeapYear()) {
maxDay = 29;
}

if (day.getValue() < maxDay) {
day.setValue(day.getValue()+1);
} else {
day.setValue(1);
if (day.month.getValue() < 12) {
day.month.setValue(day.month.getValue()+1);
} else {
day.month.setValue (1);
day.month.year.setValue(day.month.year.getValue()+1);
}
}
n--;
}

return new DateUtil(day.getValue(),day.month.getValue(),day.month.year.getValue());
}
public DateUtil getPreviousNDays(int n) {
int day1 = this.day.getValue()-n;
//int month1 = this.day.month.getValue();
//int year1 = this.day.month.year.getValue();
while (day1 < 1) {
this.day.month.setValue(day.month.getValue()-1);
if (this.day.month.getValue() < 1) {
this.day.month.setValue (12) ;
this.day.month.year.setValue(this.day.month.year.getValue()-1);
}
if (this.day.month.getValue() == 2 && this.day.month.year.isLeapYear()) {
day.mon_maxnum[1] = 29;
} else {
day.mon_maxnum[1] = 28;
}
day1 += day.mon_maxnum[this.day.month.getValue()-1];
}
//Day day2=new Day(year1,month1,day1);
return new DateUtil(day1,this.day.month.getValue(), this.day.month.year.getValue());
}
public int getDaysofDates(DateUtil date) {
int days = 0;
DateUtil earlierDate;
DateUtil laterDate;

if (compareDates(date)) {
earlierDate = this;
laterDate = date;
} else {
earlierDate = date;
laterDate = this;
}
while (earlierDate.day.month.year.getValue() < laterDate.day.month.year.getValue()
|| (earlierDate.day.month.year.getValue() == laterDate.day.month.year.getValue() && earlierDate.day.month.getValue()< laterDate.day.month.getValue())
|| (earlierDate.day.month.year.getValue() == laterDate.day.month.year.getValue() && earlierDate.day.month.getValue() == laterDate.day.month.getValue() && earlierDate.day.getValue() < laterDate.day.getValue())) {
days++;
earlierDate = earlierDate.getNextNDays(1);
}
return days;
}
}

class Day {
private int value;
Month month;
int[] mon_maxnum = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};

public Day() {
month=new Month();
}

public Day(int yearValue,int monthValue,int dayValue) {
//this.getMonth().getYear().setValue(yearValue);
month=new Month(yearValue,monthValue);
//this.getMonth().setValue(monthValue);
this.value = dayValue;
}

public Day(Month month) {
this.month = month;
}

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(){
this.value=1;
}

public void resetMax(){

this.value=mon_maxnum[month.getValue()-1];
}

public boolean validate (){
if(this.value>=1||this.value<=12){
return true;
}
return false;
}

public void monthIncrement (){
this.value+=1;
}

public void monthReduction (){
this.value-=1;
}
}

class Month {
private int value;
Year year;

public Month() {
year=new Year();
}

public Month(int yearValue,int monthValue) {
//this.getYear().setValue(yearValue);
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;
}

public void resetMin(){
this.value=1;
}

public void resetMax(){
this.value=12;
}

public boolean validate (){
if(this.value>=1||this.value<=12){
return true;
}
return false;
}

public void monthIncrement (){
this.value+=1;
}

public void monthReduction (){
this.value-=1;
}
}

class Year {
private int value;

public Year() {
super();
}

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

public int getValue() {
return value;
}

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

public boolean isLeapYear(){//判断是否为闰年
return this.value % 4 == 0 && (this.value % 100 != 0 || this.value % 400 == 0);
}

public boolean validate (){
if(this.value>=1900||this.value<=2050){
return true;
}
return false;
}

public void yearIncrement (){
this.value+=1;
}

public void yearReduction (){
this.value-=1;
}
}

 

3.题目集5的7-6

这道题与上一道题十分相近,主要是改变了类的结构设计,这样的好处是是代码耦合性更低,而且让我们体会了两种不同设计的差异。

类图:

 代码分析图

 源码:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = 0;
int month = 0;
int day = 0;

int choice = input.nextInt();

if (choice == 1) { // test getNextNDays method
int m = 0;
year = Integer.parseInt(input.next());
month = Integer.parseInt(input.next());
day = Integer.parseInt(input.next());

DateUtil date = new DateUtil(year, month, day);

if (!date.checkInputValidity()) {
System.out.println("Wrong Format");
System.exit(0);
}

m = input.nextInt();

if (m < 0) {
System.out.println("Wrong Format");
System.exit(0);
}

System.out.print(date.year.getValue() + "-" + date.month.getValue() + "-" + date.day.getValue() + " next " + m + " days is:");
System.out.println(date.getNextNDays(m).showDate());
} else if (choice == 2) { // test getPreviousNDays method
int n = 0;
year = Integer.parseInt(input.next());
month = Integer.parseInt(input.next());
day = Integer.parseInt(input.next());

DateUtil date = new DateUtil(year, month, day);

if (!date.checkInputValidity()) {
System.out.println("Wrong Format");
System.exit(0);
}

n = input.nextInt();

if (n < 0) {
System.out.println("Wrong Format");
System.exit(0);
}

System.out.print(
date.year.getValue() + "-" + date.month.getValue() + "-" + date.day.getValue() + " previous " + n + " days is:");
System.out.println(date.getPreviousNDays(n).showDate());
} else if (choice == 3) { //test getDaysofDates method
year = Integer.parseInt(input.next());
month = Integer.parseInt(input.next());
day = Integer.parseInt(input.next());

int anotherYear = Integer.parseInt(input.next());
int anotherMonth = Integer.parseInt(input.next());
int anotherDay = Integer.parseInt(input.next());

DateUtil fromDate = new DateUtil(year, month, day);
DateUtil toDate = new DateUtil(anotherYear, anotherMonth, anotherDay);

if (fromDate.checkInputValidity() && toDate.checkInputValidity()) {
System.out.println("The days between " + fromDate.showDate() +
" and " + toDate.showDate() + " are:"
+ fromDate.getDaysofDates(toDate));
} else {
System.out.println("Wrong Format");
System.exit(0);
}
}
else{
System.out.println("Wrong Format");
System.exit(0);
}
}
}

class DateUtil {
Day day;
Month month;
Year year;

int[] mon_maxnum = new int[] {31,28,31,30,31,30,31,31,30,31,30,31};

public DateUtil() {
super();
}

public DateUtil(int y,int m,int d) {
day=new Day(d);
month=new Month(m);
year=new Year(y);
}

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 stedayMax (){
day.setValue(mon_maxnum[month.getValue()-1]);
}

public boolean checkInputValidity() {
if(year.getValue()<1820||year.getValue()>2020||month.getValue()>12||month.getValue()<1||day.getValue()<1||day.getValue()>31) {
return false;
}
if(year.isLeapYear()){
if((month.getValue()==4||month.getValue()==6||month.getValue()==9||month.getValue()==11)&&day.getValue()>30)
return false;
if(month.getValue()==2&&day.getValue()>29)
return false;
}
else{
if((month.getValue()==4||month.getValue()==6||month.getValue()==9||month.getValue()==11)&&day.getValue()>30)
return false;
if(month.getValue()==2&&day.getValue()>28)
return false;
}
return true;
}
public 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;
}
}
public boolean equalTwoDates(DateUtil date) {
return (this.year.getValue() == date.year.getValue() && this.month.getValue() == date.month.getValue() && this.day.getValue() == date.day.getValue());
}
public String showDate() {
return year.getValue()+"-"+month.getValue()+"-"+day.getValue();
}
public DateUtil getNextNDays(int n) {
while (n > 0) {
int maxDay = mon_maxnum[month.getValue()-1];
if (month.getValue() == 2 && year.isLeapYear()) {
maxDay = 29;
}

if (day.getValue() < maxDay) {
day.dayIncrement();
} else {
day.setValue(1);
if (month.getValue() < 12) {
month.monthIncrement();
} else {
month.setValue (1);
year.yearIncrement();
}
}
n--;
}

return new DateUtil(year.getValue(),month.getValue(),day.getValue());
}
public DateUtil getPreviousNDays(int n) {
int day1 = this.day.getValue()-n;
//int month1 = this.day.month.getValue();
//int year1 = this.day.month.year.getValue();
while (day1 < 1) {
this.month.setValue(month.getValue()-1);
if (this.month.getValue() < 1) {
this.month.setValue (12) ;
this.year.setValue(this.year.getValue()-1);
}
if (this.month.getValue() == 2 && this.year.isLeapYear()) {
mon_maxnum[1] = 29;
} else {
mon_maxnum[1] = 28;
}
day1 += mon_maxnum[this.month.getValue()-1];
}
//Day day2=new Day(year1,month1,day1);
return new DateUtil(this.year.getValue(),this.month.getValue(),day1 );
}
public int getDaysofDates(DateUtil date) {
int days = 0;
DateUtil earlierDate;
DateUtil laterDate;

if (compareDates(date)) {
earlierDate = this;
laterDate = date;
} else {
earlierDate = date;
laterDate = this;
}
while (earlierDate.year.getValue() < laterDate.year.getValue()
|| (earlierDate.year.getValue() == laterDate.year.getValue() && earlierDate.month.getValue()< laterDate.month.getValue())
|| (earlierDate.year.getValue() == laterDate.year.getValue() && earlierDate.month.getValue() == laterDate.month.getValue() && earlierDate.day.getValue() < laterDate.day.getValue())) {
days++;
earlierDate = earlierDate.getNextNDays(1);
}
return days;
}
}

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 (){
this.value+=1;
}

public void dayReduction (){
this.value-=1;
}
}

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(){
this.value=1;
}

public void resetMax(){
this.value=12;
}

public boolean validate (){
if(this.value>=1&&this.value<=12){
return true;
}
return false;
}

public void monthIncrement (){
this.value+=1;
}

public void monthReduction (){
this.value-=1;
}
}

class Year {
private int value;

public Year() {
super();
}

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

public int getValue() {
return value;
}

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

public boolean isLeapYear(){//判断是否为闰年
return this.value % 4 == 0 && (this.value % 100 != 0 || this.value % 400 == 0);
}

public boolean validate (){
if(this.value>=1900&&this.value<=2050){
return true;
}
return false;
}

public void yearIncrement (){
this.value+=1;
}

public void yearReduction (){
this.value-=1;
}
}

 

4.题目集6的7-1

这道题是目前遇到的最难的,我将近写了一千行代码,,写了超过了30个小时,最后只得了60分,本来还有一天半的时间,但我由于之前因为写代码,好多作业没做,于是最后一天半没有再写了,总之我觉得我写代码还是太差了,应该得到练习,希望后面的pta作业我能坚持下来,在写这段代码的时候,最难的部分是由于测试例子太少了,我需要自己去debug多遍去寻找测试点的示例,这花了我好多时间,找到了测试点后,发现改了一点后,经常这个对了,其他之前对了的测试点可能又错了,这大概率是我的代码设计的太烂了,导致耦合性太高,一动激发全身,所以我觉得在写代码之前一定要思考好怎么写,大致方向确定后再写,这个时间可能长达几个小时以上,但我觉得很重要。

类图:

 代码分析图:

 源码:

import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
public class Main {
public static void main(String[] args) {
Waiter waiter=new Waiter();
waiter.plays();
}
}

class Waiter {
private final AbstractMenu menu=new Meun();
private DiscountCalculator discountCalculator=new DiscountCalculator();
private ArrayList<Table> tablelist=new ArrayList<>();
private double discount=0;
private String go;
Scanner in = new Scanner(System.in);
private int flog=0;
private int judgeLegal=0;

private ArrayList<Boolean>judgeRecordlsit=new ArrayList<>();
//添加菜单
public void plays (){

go=in.nextLine();
//添加菜单
addMenu(go);
if(!go.startsWith("table")){
System.exit(0);
}
if(go.startsWith("table")){

//添加桌号,计算折扣
calculator(go);
//添加订单,删除订单,代点菜
// addAndDeleteRecords(go);

}
//计算总价
if(tablelist.size()!=0){
TotalPrice();
}
ending(go);

}
//添加菜单
public void addMenu (String dishAndPrice){
String[] a=dishAndPrice.split(" ");
String dishName=a[0];
int price=0;
String pecialities;

while(!a[0].equals("table")&&(a.length==2||a.length==3)){
int flog1=0;
dishName=a[0];
if((a.length!=2&&a.length!=3)||(a.length==3&&!a[2].equals("T"))||!(judgeNum(a[1]))){
System.out.println("wrong format");
flog1=1;
}
if(judgeNum(a[1])){
price= Integer.parseInt(a[1]);
}
if(flog1==0){
if(a.length==2){
pecialities="hgx";
this.menu.addDish(dishName,price,pecialities);
} else if (a.length==3) {
pecialities=a[2];
this.menu.addDish(dishName,price,pecialities);
}
judgeNum(a[1]);
if (price<=0||price>=300) {
System.out.println(dishName+" price out of range "+price);
}
}

this.go=in.nextLine();
if(judgeline(this.go)){
System.out.println("wrong format");
this.go=in.nextLine();
a = this.go.split(" ");
}else {
a = this.go.split(" ");
}
}
}

//计算折扣,设置桌号
public void calculator(String tableAndtime){
String pattern = "table \\d+ \\d{4}/\\d{1,2}/\\d{1,2} \\d{1,2}/\\d{1,2}/\\d{1,2}";

String str= String.valueOf(tableAndtime.charAt(tableAndtime.length()-1));
String[] b=tableAndtime.split(" ");
int flog1=0;
int flog2=0;
int flog3=0;

while (b[0].equals("table")){
if(tableAndtime.matches(pattern)){
//判断桌号是否合法
int tableNum=1;
if(!judgeNum(b[1])){
System.out.println("wrong format");
flog1=1;
}else {
tableNum= Integer.parseInt(b[1]);
}
//判断时间数据是否合法
this.discount=discountCalculator.discountCalculator(1,b[2], b[3], "hgx");
if (discount==-4) {
flog1=1;
flog2=1;
}
//判断日期数据是否合法
if(discount==-1){
flog1=1;
flog2=1;
}
//判断桌号是否合法
if(!judgetableNum(b[1])){
flog1=1;
flog2=2;
}
if(flog1==0){
Table table=new Table(b[0],tableNum);
tablelist.add(table);
tablelist.get(tablelist.size()-1).setDate(b[2]);
tablelist.get(tablelist.size()-1).setTime(b[3]);
this.go=in.nextLine();
b=this.go.split(" ");
//判断是否记录不是以“table”开头
if(!b[0].equals("table")&&!judgeNum(b[0])&&b.length>2){
this.go=in.nextLine();
addAndDeleteRecords(go);
b=this.go.split(" ");
} else {
addAndDeleteRecords(go);
b=this.go.split(" ");
}
} else if (flog1==1) {//桌号异常
this.go=in.nextLine();
b=this.go.split(" ");
while (!b[0].equals("table")&&!b[0].equals("end")){
if(b.length<4) {
flog3 = 1;
}
this.go = in.nextLine();
b = this.go.split(" ");
}
if((flog2!=0&&flog3==1)){
System.out.println("wrong format");
} else if (flog2==1&&(this.discount==-4||this.discount==-1)) {
System.out.println(tableNum+ " date error");
} else if (flog2==2) {
System.out.println(tableNum +" table num out of range");
}
flog1=0;
}
}else {
System.out.println("wrong format");
this.go=in.nextLine();
b=this.go.split(" ");
}
}
}
//添加订单,删除订单,代点菜
public void addAndDeleteRecords(String recordInformation){
//输出桌号
System.out.println(tablelist.get(tablelist.size()-1).getTable() + " " + tablelist.get(tablelist.size()-1).getTableNum()+": ");
String[] c=recordInformation.split(" ");
while (!c[0].equals("table")&&c.length!=5&&!c[0].equals("end")&&!c[1].equals("delete")) {


//判断混合的菜谱信息(菜谱信息忽略)
while (!c[0].equals("table") && c.length == 2) {
System.out.println("invalid dish");
this.go = in.nextLine();
c = this.go.split(" ");
}
//添加订单
//判断格式
String pattern = "^[0-9]+\\s+[\\u4e00-\\u9fa5]+\\s+[0-9]+\\s+[0-9]+$";
if (this.go.matches(pattern)) {
Order order01=new Order();
while (c.length == 4 && !c[1].equals("delete") && c[0].matches("\\d")) {
int orderNum = Integer.parseInt(c[0]);
String dishName = c[1];
int portion = Integer.parseInt(c[2]);
int num = Integer.parseInt(c[3]);
order01.addARecord(orderNum, dishName, portion, num);
this.go = in.nextLine();
c = this.go.split(" ");
if (!c[0].equals("table") && !judgeNum(c[0]) && !c[0].equals("end")) {
this.go = in.nextLine();
c = this.go.split(" ");
}
}
for (Record record : order01.getRecords()) {
boolean isMerged = false;
for (Record mergedRecord : tablelist.get(tablelist.size() - 1).getOrder().getRecords()) {
if (mergedRecord.getDishName().equals(record.getDishName())&&mergedRecord.getPortion()==record.getPortion()) {
mergedRecord.setNum(mergedRecord.getNum() + record.getNum());
isMerged = true;
break;
}
}
if (!isMerged) {
tablelist.get(tablelist.size() - 1).getOrder().addARecord(record.getOrderNum(), record.getDishName(), record.getPortion(), record.getNum());
}
}
} else {
System.out.println("wrong format");
this.go = in.nextLine();
c = this.go.split(" ");

}
}
//删除重复的订单
//输出部分订单;
Iterator<Record> iter = tablelist.get(tablelist.size()-1).getOrder().getRecords().iterator();
ArrayList<Integer>flog2=new ArrayList<>();
while(iter.hasNext()) {

int flog1=0;
Record record1 = iter.next();
flog2.add(record1.getOrderNum());
Dish dish = this.menu.searchDish(record1.getDishName());
if(dish != null) {
//份额超出范围
if(((record1.getPortion()!=1&&record1.getPortion()!=2&&record1.getPortion()!=3)&&menu.searchDish(record1.getDishName())!=null&& !Objects.equals(menu.searchDish(record1.getDishName()).getSpecialities(), "T"))||
((record1.getPortion()!=1&&record1.getPortion()!=2&&record1.getPortion()!=3)&&menu.searchDish(record1.getDishName())!=null&& Objects.equals(menu.searchDish(record1.getDishName()).getSpecialities(), "T"))){
System.out.println(record1.getOrderNum()+" portion out of range "+record1.getPortion());
flog1++;
}
//份数超出范围
if(record1.getNum()>15) {
System.out.println(record1.getOrderNum() + " num out of range " + record1.getNum());
flog1++;
}
if(flog1>0){
this.judgeRecordlsit.add(false);
}else {
this.judgeRecordlsit.add(true);
}
record1.setDish(dish);
if(this.judgeRecordlsit.get(this.judgeRecordlsit.size()-1)){

if(flog2.size()!=1&&flog2.get(flog2.size()-2)>= record1.getOrderNum()){
System.out.println("record serial number sequence error");

}
if(flog2.size()==1||flog2.get(flog2.size()-2)< record1.getOrderNum()){
System.out.println(record1.getOrderNum() + " " + record1.getDish().getName() + " " + record1.getPrice());
}

}
} else {
System.out.println(record1.getDishName() + " " + "does not exist");
iter.remove();
}
}
//代点菜
while (c.length==5&&!c[1].equals("delete")){
int flog1=0;
int tableNum= Integer.parseInt(c[0]);//桌号
int orderNum= Integer.parseInt(c[1]);
String dishName=c[2];
int portion= Integer.parseInt(c[3]);
int num= Integer.parseInt(c[4]);
//份额超出范围
if((portion<1||portion>3&& !Objects.equals(this.menu.searchDish(dishName).getSpecialities(), "T"))||
((portion!=1&&portion!=3)&& Objects.equals(this.menu.searchDish(dishName).getSpecialities(), "T"))){
System.out.println(dishName+" portion out of range "+num);
flog1++;
}
//份数超出范围
if(num>15){
System.out.println(dishName+" num out of range "+num);
flog1++;
}
if(flog1>0){
this.judgeRecordlsit.add(false);
}else {
this.judgeRecordlsit.add(true);
}
////判断桌号是否存在
if(judgetableNumExist(tableNum)){
int flog=0;
tablelist.get(tablelist.size()-1).getOrder().addARecord(orderNum,dishName,portion,num);
Iterator<Record> iter1 = tablelist.get(tablelist.size()-1).getOrder().getRecords().iterator();
while(iter1.hasNext()) {
Record record1 = iter1.next();
Dish dish = this.menu.searchDish(record1.getDishName());
if(dish != null) {
record1.setDish(dish);
} else {
flog++;
System.out.println(record1.getDishName() + " " + "does not exist");
this.judgeRecordlsit.remove(this.judgeRecordlsit.size()-1);
iter1.remove();
}
}
if(flog==0){
System.out.println(orderNum+" table "+tablelist.get(tablelist.size()-1).getTableNum()+" pay for table "+tableNum+" "+
this.menu.searchDish(dishName).getPrice(portion));
}

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

this.go=in.nextLine();
c=this.go.split(" ");
}
//删除订单
while(!c[0].equals("end")&&c.length==2&&c[1].equals("delete")){
int flog1=0;
int orderNum= Integer.parseInt(c[0]);
if((judgeorderNum(orderNum)&&(tablelist.size() > 0 && tablelist.get(tablelist.size()-1).getOrder() != null))||this.flog==1){
ListIterator<Record> iter2 = tablelist.get(tablelist.size()-1).getOrder().getRecords().listIterator();
while ((iter2.hasNext())){
Record record1 = iter2.next();
if ((record1 != null &&record1.getOrderNum() == orderNum)||this.flog==1) {
//tablelist.get(tablelist.size() - 1).getOrder().delARecordByOrderNum(orderNum);
if(this.flog==1){
this.flog++;
}else {
iter2.remove();
this.judgeRecordlsit.remove(this.judgeRecordlsit.size() - 1);
this.flog++;
}

}
}
}else {
flog1++;
}
if(this.flog>1){
System.out.println("deduplication "+orderNum);
}
if(flog1!=0){
System.out.println("delete error;");
}
this.go=in.nextLine();
c=this.go.split(" ");
}
this.flog=0;
}
//判断号码是否是合法格式
public boolean judgeNum(String num){
if(num.matches("^[1-9]\\d*$")){
return true;
}else{
return false;
}
}
//判断是否为空行
public boolean judgeline(String str){
if (str.isEmpty()) {
return true;
}
return false;
}
//判断订单是否存在
public boolean judgeorderNum(int num){
for(Record record1:tablelist.get(tablelist.size()-1).getOrder().getRecords()){
if(record1.getOrderNum()==num){
return true;
}
}
return false;
}
//判断桌号是否超出范围
public boolean judgetableNum (String str){
int num;
try {
num=Integer.parseInt(str);
if(num>=1&&num<=55){
return true;
}else {
return false;
}
} catch (NumberFormatException e) {
return false;
}
}

//判断桌号是否存在
public boolean judgetableNumExist (int num){
for(Table list:tablelist){
if(list.getTableNum()==num){
return true;
}
}
return false;
}
//结束
public void ending (String end){
if(end.equals("end")){
System.exit(0);
}

}
public void TotalPrice(){
int flog1=0;
for(Table table:tablelist){
int i=0;
double totalNodiscount=0;

for(Record record1:table.getOrder().getRecords()){
if(this.judgeRecordlsit.get(i)==true){
this.discount=discountCalculator.discountCalculator(table.getTableNum(),table.getDate(),
table.getTime(), this.menu.searchDish(record1.getDishName()).getSpecialities());
totalNodiscount+=record1.getPrice();
table.setTotalPrice((int) Math.round(table.getTotalPrice()+record1.getPrice()*this.discount));
}
i++;
}
if(discount==-3){
System.out.println(table.getTable()+" "+table.getTableNum()+" out of opening hours");
continue;
} else if (discount==-2) {
System.out.println("not a valid time period");
} else if (discount==-4) {
System.out.println("wrong format");
System.exit(0);
}
flog1++;
if(flog1==1){
System.out.print(table.getTable()+" "+table.getTableNum()+": "+Math.round(totalNodiscount)+" "+table.getTotalPrice());
} else if (flog1>1) {
System.out.println();
System.out.print(table.getTable()+" "+table.getTableNum()+": "+Math.round(totalNodiscount)+" "+table.getTotalPrice());
}
}
}
}

abstract class AbstractDish {
private String name;//菜品名称

private int unit_price; //单价
private String Specialities;//特色菜

public AbstractDish(String name, int unit_price, String specialities) {
this.name = name;
this.unit_price = unit_price;
this.Specialities = specialities;
}

public AbstractDish() {
}

public String getName() {
return name;
}

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

public int getUnit_price() {
return unit_price;
}

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

public String getSpecialities() {
return Specialities;
}

public void setSpecialities(String specialities) {
Specialities = specialities;
}

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

abstract class AbstractMenu {
private ArrayList<Dish> dishes = new ArrayList<>();

// 构造函数
public AbstractMenu() {
}

public AbstractMenu(ArrayList<Dish> dishes) {
this.dishes = dishes;
}

public ArrayList<Dish> getDishes() {
return dishes;
}

public void setDishes(ArrayList<Dish> dishes) {
this.dishes = dishes;
}

// 根据菜名在菜谱中查找菜品信息,返回Dish对象
public abstract Dish searchDish(String dishName) ;

// 添加一道菜品信息
public abstract ArrayList<Dish> addDish(String dishName, int unit_price,String Specialities) ;
}

abstract class AbstractOrder {
private ArrayList<Record> records=new ArrayList<>();//保存订单上每一道的记录

public AbstractOrder() {
}

public AbstractOrder(ArrayList<Record> records) {
this.records = records;
}

public List<Record> getRecords() {
return records;
}

public void setRecords(ArrayList<Record> records) {
this.records = records;
}

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

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

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

public abstract Record findRecordByNum(int orderNum);//根据序号查找一条记录
}

abstract class AbstractRecord {
private int orderNum;//序号

private Dish d;//菜品
private String dishName;//菜名

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

public AbstractRecord() {
}

public AbstractRecord(int orderNum, String dishName, int portion, int num) {
this.orderNum = orderNum;
this.dishName = dishName;
this.portion = portion;
this.num = num;
}

 

public String getDishName() {
return dishName;
}

public void setDishName(String dishName) {
this.dishName = dishName;
}

public int getOrderNum() {
return orderNum;
}

public void setOrderNum(int orderNum) {
this.orderNum = orderNum;
}

public Dish getDish() {
return d;
}

public void setDish(Dish d) {
this.d = d;
}

public int getPortion() {
return portion;
}

public void setPortion(int portion) {
this.portion = portion;
}

public int getNum() {
return num;
}

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

public abstract int getPrice();//计价,计算本条记录的价格
}


class DiscountCalculator implements interfaceDiscountCalculator{

@Override
public double discountCalculator( int tableNum,String date, String time,String Specialities) {
// 解析日期和时间
String[] dateParts = date.split("/");
String[] timeParts = time.split("/");
int year=0,month=0,day=0,hour=0,minute=0,second=0;
year = Integer.parseInt(dateParts[0]);
month = Integer.parseInt(dateParts[1]);
day = Integer.parseInt(dateParts[2]);
hour = Integer.parseInt(timeParts[0]);
minute = Integer.parseInt(timeParts[1]);
second = Integer.parseInt(timeParts[2]);
//判断时间数据是否合法
if(!isValidTime(hour,minute,second)){
return -4;
}


// 检查日期是否合法
if (!isValidDate(year, month, day)) {
return -4;
}
// 判断时间是否超出范围
LocalDate startDate = LocalDate.of(2022, 1, 1);
LocalDate endDate = LocalDate.of(2023, 12, 31);
LocalDate inputDate = LocalDate.of(year, month, day);

if (inputDate.isBefore(startDate) || inputDate.isAfter(endDate)) {
return -2;
}

// 检查时间是否在营业时间范围内
if (!isInOpeningHours(hour, minute, second, dayOfWeek(year, month, day))) {
return -3;
}

// 计算折扣
if (isWeekend(dayOfWeek(year, month, day))) {
return 1.0;

} else if (!isWeekend(dayOfWeek(year, month, day))&&Specialities.equals("T")) {
return 0.7;
} else if (isLunchTime(hour, minute)&&!Specialities.equals("T")) {
return 0.6;
} else if (isEveningTime(hour, minute)&&!Specialities.equals("T")) {
return 0.8;
} else {
return 0.0;
}
}
@Override
// 判断日期是否合法
public boolean isValidDate(int year, int month, int day) {
try {
LocalDate.of(year, month, day);
return true;
} catch (DateTimeException e) {
return false;
}
}
@Override
// 判断时间是否在营业时间范围内
public boolean isInOpeningHours(int hour, int minute, int second, int dayOfWeek) {
LocalTime time = LocalTime.of(hour, minute, second);
if (dayOfWeek == DayOfWeek.SATURDAY.getValue() || dayOfWeek == DayOfWeek.SUNDAY.getValue()) {
return !time.isBefore(LocalTime.of(9, 30)) && !time.isAfter(LocalTime.of(21, 30));
} else {
return (!time.isBefore(LocalTime.of(10, 30)) && !time.isAfter(LocalTime.of(14, 30)))
|| (!time.isBefore(LocalTime.of(17, 0)) && !time.isAfter(LocalTime.of(20, 30)));
}
}
@Override
// 判断是否为周末
public boolean isWeekend(int dayOfWeek) {
return dayOfWeek == DayOfWeek.SATURDAY.getValue() || dayOfWeek == DayOfWeek.SUNDAY.getValue();
}
@Override
// 判断是否为中午餐时间
public boolean isLunchTime(int hour, int minute) {
LocalTime time = LocalTime.of(hour, minute);
return !time.isBefore(LocalTime.of(10, 30)) && !time.isAfter(LocalTime.of(14, 30));
}
@Override
// 判断是否为晚餐时间
public boolean isEveningTime(int hour, int minute) {
LocalTime time = LocalTime.of(hour, minute);
return !time.isBefore(LocalTime.of(17, 0)) && !time.isAfter(LocalTime.of(20, 30));
}
@Override
// 计算星期几
public int dayOfWeek(int year,int month,int day){
DayOfWeek dayOfWeek = LocalDate.of(year, month, day).getDayOfWeek();
return dayOfWeek.getValue();
}
//判断传入的数据是否合法
@Override
public boolean isLegal(String s) {
return s.length() == 2 || s.length() == 1;
}
public boolean isValidTime(int hour, int minute, int second) {
try {
LocalTime time = LocalTime.of(hour, minute, second);
return true;
} catch (Exception e) {
return false;
}
}
}

class Dish extends AbstractDish{

public Dish(String name, int unit_price, String specialities) {
super(name, unit_price, specialities);
}

public Dish() {
}

// 计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份)
public int getPrice(int portion) {
switch (portion) {
case 1: return this.getUnit_price(); // 小份菜的价格=菜品的基础价格
case 2: return Math.round(this.getUnit_price() * 1.5f); // 中份菜的价格=菜品的基础价格*1.5
case 3: return this.getUnit_price() * 2; // 大份菜的价格=菜品的基础价格*2
default: return -1; // 无效的份额
}
}
}

interface interfaceDiscountCalculator {
// 检查日期是否合法
// 检查时间是否在营业时间范围内
// 计算折扣
double discountCalculator( int tableNum,String date, String time,String Specialities);
// 判断日期是否合法
boolean isValidDate(int year, int month, int day);
// 判断时间是否在营业时间范围内
boolean isInOpeningHours(int hour, int minute, int second, int dayOfWeek);
// 判断是否为周末
boolean isWeekend(int dayOfWeek);
// 判断是否为中午餐时间
boolean isLunchTime(int hour, int minute);
// 判断是否为晚餐时间
boolean isEveningTime(int hour, int minute);
// 计算星期几
int dayOfWeek(int year,int month,int day);
boolean isLegal(String s);
}

class Meun extends AbstractMenu{
// 构造函数
public Meun() {
}

public Meun(ArrayList<Dish> dishes) {
super(dishes);
}

@Override
// 根据菜名在菜谱中查找菜品信息,返回Dish对象
public Dish searchDish(String dishName) {
for (Dish dish : this.getDishes()) {
if (dish.getName().equals(dishName)) {
return dish;
}
}
return null; // 如果未找到,则返回null

}
@Override
// 添加一道菜品信息
public ArrayList<Dish> addDish(String dishName, int unit_price,String Specialities) {
for(Dish dish:getDishes()){
if(dish.getName()==dishName){
this.getDishes().remove(dish);
}
}

Dish newDish = new Dish(dishName, unit_price,Specialities);
this.getDishes().add(newDish);
return this.getDishes();
}
}

class Order extends AbstractOrder{
public Order() {
}

public Order(ArrayList<Record> records) {
super(records);
}

@Override
public int getTotalPrice() {

return 0;
}
// 添加一条菜品信息到订单中
@Override
public Record addARecord(int orderNum, String dishName, int portion, int num) {
Record record = new Record(orderNum,dishName, portion, num);
this.getRecords().add(record);
return record;
}
// 删除一条菜品信息从订单中
@Override
public void delARecordByOrderNum(int orderNum) {
for (int i = 0; i < this.getRecords().size(); i++) {
if (this.getRecords().get(i).getOrderNum() == orderNum) {
this.getRecords().remove(i);
//i--; // 删除后需要更新i的值
}
}
}

//根据序号查找一条记录
@Override
public Record findRecordByNum(int orderNum) {
for (Record record : this.getRecords()) {
if(record.getOrderNum()==orderNum) {
return record;
}
}
return null;
}
}

class Record extends AbstractRecord{
public Record() {
}

public Record(int orderNum, String dishname, int portion, int num) {
super(orderNum, dishname, portion, num);
}

@Override
public int getPrice() {

return this.getDish().getPrice(this.getPortion())*this.getNum();
}
}

class Table {
private String table;
private int tableNum=0;
private AbstractOrder order=new Order();
private int recordPrice=0;
private String date;
private String time;

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}

public String getTime() {
return time;
}

public void setTime(String time) {
this.time = time;
}

public int getRecordPrice() {
return recordPrice;
}

public void setRecordPrice(int recordPrice) {
this.recordPrice = recordPrice;
}

private int totalPrice;

public int getTotalPrice() {
return totalPrice;
}

public void setTotalPrice(int totalPrice) {
this.totalPrice = totalPrice;
}

public AbstractOrder getOrder() {
return order;
}

public void setOrder(AbstractOrder order) {
this.order = order;
}

public Table() {
}

public Table(String table, int tableNum) {
this.table = table;
this.tableNum = tableNum;
}

public String getTable() {
return table;
}

public void setTable(String table) {
this.table = table;
}

public int getTableNum() {
return tableNum;
}

public void setTableNum(int tableNum) {
this.tableNum = tableNum;
}

}

 

 

(3)采坑心得:

1.Java 版本问题:不同版本的 Java 可能会导致代码不兼容,因此要注意使用哪个版本。

2.类型转换问题:在 Java 中需要注意类型转换,尤其是强制类型转换,避免出现 ClassCastException 等错误。

3.数组越界问题:在使用数组时需要注意数组越界问题,避免出现 ArrayIndexOutOfBoundsException 等错误,所以我再这段代码中没有使用数字,使用了list集合。

4.空指针问题:Java 中经常出现空指针异常,需要对可能为空的对象进行判断,避免出现 NullPointerException 等错误,我在删除订单的时候刚开始使用foreche遍历删除,后面发现会出现这个问题,然后我使用了Iterator发现也不能使用,最后查询使用了LinkIterator,解决了这个问题。

5.注解问题:Java 中的注解机制需要理解其作用和使用方式,否则可能会出现编译错误或运行时异常。

6.设计问题:这个是最重要的,在得了60之后,我有写了8个小时,这段时间我感觉就是因为设计的不好,导致一直在那循环,这个对了,那个又错了,可惜最后没有时间再去重写了,真的设计很重要,设计很重要,我要说三遍。

(4)改进建议:

 

 

我觉得再pta第六次作业里面,应该在进行下一次升级,把一些设计模式和需要去扩展的地方加在里面,提高我们的设计思维。

(5)总结:

  

一、学到了什么

Java基础知识:学习了Java语言的基本语法、变量、运算符、控制语句等基础知识。

面向对象编程:掌握了Java的面向对象编程思想和相关的知识,如类、对象、封装、继承、多态等。

集合框架:了解了Java集合框架的基本概念和使用,包括List、Set、Map等。

异常处理:了解了Java异常处理的概念和基本使用,能够正确处理异常。

二、需要进一步学习及研究的地方

算法和数据结构:在PTA上做题需要掌握一定的算法和数据结构知识,这是一个需要长期学习和研究的领域。

面向对象设计模式:了解更多的设计模式,如工厂模式、单例模式、观察者模式等,能够更好地设计和开发Java应用程序。

三、对教师、课程、作业、实验、课上及课下组织方式等方面的改进建议及意见

教师可以多讲解一些实际的开发案例和项目,让学生更好地了解Java开发的实际应用场景。

课程内容可以更加贴近实际开发需求,提供更多的实践机会和案例,让学生更好地掌握和应用Java知识。

作业和实验可以更加具有挑战性和实践性,让学生更有动力和兴趣去学习和探究Java编程。

课上和课下可以有更多的交流和讨论机会,让学生互相学习和分享经验,提高学习效率和效果。

对于PTA等在线编程练习平台的使用,可以提供更加详细和有针对性的指导和教学,让学生更好地利用这些平台进行编程练习。