首页 > 其他分享 >PTA题目集4、5、6以及期中考试的总结

PTA题目集4、5、6以及期中考试的总结

时间:2023-11-19 22:25:17浏览次数:40  
标签:lineArray 题目 期中考试 System PTA int return order out

一、前言

在过去做完的PTA题目集4、5、6以及期中考试,相比前几次的题目集来说难度都相对提高了许多,对于基础相对比较薄弱的我做起来也比较吃力,但是题量比之前都少了很多,后两次题目集都只有菜单计价程序一题,最主要的也还是菜单计价程序这一类题目,代码量很大。这类题目对于类的考察相当之高,类与类之间的调用对我们来说令整体难度加深了许多,对我们的java能力有着很大的考验。

二、设计与分析

第四次题目集

7-1菜单计价程序-3

这一道题相对于菜单几家程序-2增加的部分要求为:

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

分析:菜单计价程序-3相较于2新增加了桌号标以及代点菜等信息,营业时间等。对于前面来说,虽说是延续着之前的模板,但难度也还是增加了不少,不仅对于功能的增加过多,同时需要根据时间来将之前的菜品打折扣,某方面来说要更改先前部分的逻辑,增添新的东西,进而使得闭环更加复杂。

类图:

 

我的源码:

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
class Main{
public static void main(String[] args) {
int countOfOrder = 0;
Menu menu = new Menu();
Order order = new Order();
operator operator = new operator();
operator.recorddish(menu);
operator.recordorderNum(order);
operator.recordtime(order);
operator.orderdish(order,menu);

operator.output(order);
}

}
class operator {
Scanner in = new Scanner(System.in);
public void output(Order order) {
boolean flag = true;
for (int j = 0; flag; j++) {
float totalCost = 0;
if(order.judgeTime(order) == -1){
System.out.println("table " + order.getTableNum() + " out of opening hours");
}else {
System.out.println("table " + order.getTableNum() + ": ");
for (int i = 0; ; i++) {
if (order.record[i].getOrderNum() != -1) {
if (order.record[i].getIsValue() == 1) {
totalCost = totalCost + order.record[i].getPrice();
}
System.out.println(order.record[i].orderNum + " " + order.record[i].getD().getName() + " " + order.record[i].getPrice());
} else {
totalCost = totalCost * order.judgeTime(order);
if (totalCost - (int) totalCost >= 0.5) {
totalCost = (int) totalCost + 1;
}

System.out.println("table " + order.getTableNum() + ": " + (int) totalCost);
break;
}
}
}
flag = false;
}

}
public void recorddish(Menu menu) {
int price;
String name;
for (int i = 0; ; i++) {
name = in.next();
if (name.equals("table")) {
break;
}
price = in.nextInt();
menu.addDish(name, price);
}
}

public void recordorderNum(Order order) {
order.setTablenum(in.nextInt());
}

public void recordtime(Order order) {
int Year = 0,Month = 0,Day = 0,Hour = 0,Min = 0,Sec = 0;
String[] time = in.nextLine().replace("/"," ").split(" ");
Year = Integer.parseInt(time[1]);
Month = Integer.parseInt(time[2]);
Day = Integer.parseInt(time[3]);
Hour = Integer.parseInt(time[4]);
Min = Integer.parseInt(time[5]);
Sec = Integer.parseInt(time[6]);
order.setYear(Year);
order.setMonth(Month);
order.setDay(Day);
order.setHours(Hour);
order.setMin(Min);
order.setSec(Sec);
}

boolean orderdish(Order order, Menu menu) {
boolean result = true;
for (int i = 0; result; i++) {
int Num = 0;
String Nums = in.next();
if (Nums.equals("end")){
result = false;
break;
}else{
Num = Integer.parseInt(Nums);
}
String dish = in.next();
if(dish.equals("delete")){
order.delARecordByOrderNum(Num);
} else {
order.record[i].isValue = 1;
order.record[i].setOrderNum(Num);
order.record[i].setD(menu.searchDish(dish));
order.record[i].setPortion(in.nextInt());
order.record[i].setOrderQuantity(in.nextInt());
}
}
return result;
}

void deleteRecord(Order order, int recordNum) {
order.delARecordByOrderNum(recordNum);
}

}
class Dish {
Dish(String name, int unit_price) {
this.name = name;
this.unit_price = unit_price;
}

String name;

int unit_price;

int getprice(int portion) {
double cost = 0;
if (portion == 1) {
cost = unit_price;
} else if (portion == 2) {
cost = unit_price * 1.5;
} else if (portion == 3) {
cost = unit_price * 2;
}
int result = 0;
if (cost - (int) cost >= 0.5) {
result = (int) cost + 1;
} else {
result = (int) cost;
}
return result;
}

String getName() {
return name;
}

int getUnit_price() {
return unit_price;
}

}
class Menu {
Dish[] dishs = new Dish[1000];
int dishIndex = 0;

Dish searchDish(String dishName) {
boolean existDish = false;
Dish result = new Dish("0", 0);
for (int i = 0; i < 1000 ; i++) {
if (this.dishs[i].getName().equals(dishName)) {
result = dishs[i];
existDish = true;
break;
}
}
if (existDish == false) {
System.out.println(dishName + "does not exist");
}
return result;
}

void addDish(String dishName, int unit_price) {
dishs[dishIndex] = new Dish(dishName, unit_price);
dishIndex++;
}

}
class Record {
int orderNum;
Dish d;
int orderQuantity;
int isValue = 0;
int portion;
int getPrice() {
return this.orderQuantity * d.getprice(portion);
}
Record(){

}
Record(int orderNum, String name, int orderQuantity, int portion) {
setOrderNum(orderNum);
setPortion(portion);
setOrderQuantity(orderQuantity);
}

int getOrderNum() {
return orderNum;
}

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

int getIsValue() {
return isValue;
}

void setIsValue(int isValue) {
this.isValue = isValue;
}

Dish getD() {
return d;
}

void setD(Dish d) {
this.d = d;
}

int getOrderQuantity() {
return orderQuantity;
}

void setOrderQuantity(int orderQuantity) {
this.orderQuantity = orderQuantity;
}

int getPortion() {
return portion;
}

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

}
class Order {
Record[] record = new Record[100];

int tableNum;

Order(){
for(int i = 0 ;i < 100 ;i++){
this.record[i] = new Record(-1,"1",-1,-1);// 实例化创建内存
}
}
float judgeTime(Order order) {
int week = 3;
float discount = 1;
LocalDate timeStander = LocalDate.of(1898, 12, 19);// 设置参照时间1000年1月1 星期三
LocalDate time = LocalDate.of(order.getYear(), order.getMonth(), order.getDay());
week = ((int) timeStander.until(time, ChronoUnit.DAYS) + week) % 7;// 计算当前星期几
if (week >= 1 && week <= 5) {
if (order.getHours() >= 17 && order.getHours() < 20 && order.getMin() < 60 && order.getMin() >= 0 || order.getHours() == 20 && order.getMin() <= 30 && order.getMin() >= 0) {
discount = 0.8F;
}
else if (order.getHours() > 10 && order.getHours() < 14 && order.getMin() < 60 && order.getMin() >= 0 || order.getHours() == 10 && order.getMin() <= 30 && order.getMin() >= 0 || order.getHours() == 14 && order.getMin() <= 30 && order.getMin() >= 0) {
discount = 0.6F;
}
else {
discount = -1;
}

} else {
if (order.getHours() > 9 && order.getHours() < 21 && order.getMin() < 60 && order.getMin() >= 0 || order.getHours() == 9 && order.getMin() <= 30 && order.getMin() >= 0) {
discount = 1;
}
else {
discount = -1;
}
}
return discount;
}
int getTableNum() {
return tableNum;
}

void setTablenum(int tableNum) {
this.tableNum = tableNum;
}

int year, month, day, hours, min, sec;

int getYear() {
return year;
}

void setYear(int year) {
this.year = year;
}

int getMonth() {
return month;
}

void setMonth(int month) {
this.month = month;
}

int getDay() {
return day;
}

void setDay(int day) {
this.day = day;
}

int getHours() {
return hours;
}

void setHours(int hours) {
this.hours = hours;
}

int getMin() {
return min;
}

void setMin(int min) {
this.min = min;
}

int getSec() {
return sec;
}

void setSec(int sec) {
this.sec = sec;
}

int getTotalPrice() {
int sum = 0;
for (int i = 0; i <= recordindex; i++) {
if(record[i].getIsValue() == 1){
sum = sum + record[i].getPrice();
}
}
return sum;
}

static int recordindex = 0;

Record addARecord(int orderNum, String name, int orderQuantity, int portion, Menu menu) {
this.record[recordindex] = new Record(orderNum, name, orderQuantity, portion);
recordindex++;
return this.record[recordindex - 1];
}

void delARecordByOrderNum(int orderNum) {
int i = 0;
for (i = 0; ; i++) {
if (record[i].orderNum == orderNum) {
record[i].setIsValue(0);
break;
}
}
}

Record findRecordByNum(int orderNum) {
int i = 0;
for (i = 0; ; i++) {
if (orderNum == record[i].orderNum) {
record[i].isValue = 0;
break;
}
}
return record[i];
}

}

总结:这一道题我做的并不是很好,我新建了Table类来处理不同桌可能会出现的不同的问题,使对应其桌号来统计订单,而让Order类的属性,来记录Table类中对应不同桌号的点菜记录,但还是有相当多的测试点出错,对我来说难度还是比较大的,无法顺利完成。

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

这一题是这三个题目集相对来说难度适中的题目,考察的范围也不多,做起来也相对轻松点。

从键盘输入两个日期,格式如:2022-06-18。判断两个日期的先后,并输出它们之间间隔的天数、周数(不足一周按0计算)。

分析:了解Scanner类中nextLine()等方法、String类中split()等方法、Integer类中parseInt()等方法的用法,了解LocalDate类中of()、isAfter()、isBefore()、until()等方法的使用规则,了解ChronoUnit类中DAYS、WEEKS、MONTHS等单位的用法。

我的具体思路为:先将数据通过split()分割,将数据转化为int类型,再调用LocalDate类中合适的方法达到题目要求。

源码:

import java.util.Scanner;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class Main{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String Date1 = input.nextLine();
String Date2 = input.nextLine();
String []split1 = Date1.split("-");
String []split2 = Date2.split("-");
LocalDate date1 = LocalDate.of(Integer.parseInt(split1[0]),Integer.parseInt(split1[1]),Integer.parseInt(split1[2]));
LocalDate date2 = LocalDate.of(Integer.parseInt(split2[0]),Integer.parseInt(split2[1]),Integer.parseInt(split2[2]));
if(date1.isAfter(date2)) {
System.out.println("第一个日期比第二个日期更晚");
System.out.println("两个日期间隔" + ChronoUnit.DAYS.between(date2, date1) + "天");
System.out.print("两个日期间隔" + ChronoUnit.WEEKS.between(date2, date1) + "周");
}
else {
System.out.println("第一个日期比第二个日期更早");
System.out.println("两个日期间隔" + ChronoUnit.DAYS.between(date1, date2) + "天");
System.out.print("两个日期间隔" + ChronoUnit.WEEKS.between(date1, date2) + "周");
}
}
}

第五次题目集

7-1 菜单计价程序-4

这次菜单计价题目相较于上次有了很大的完善,虽然还有个别测试点没过,但功能也还算比较齐全,完成度还可以。这次是上次的加强版,加了一些新功能和一堆新的判断,PTA中测试点也是围绕这些新的判断来进行评测得分的。改变最大的的便是信息输入问题得到解决,通过字符串分割后数组中的一些特殊信息来相对准确的对号入座,循环也是借此来输入多条类似信息,保证信息能够准确的输入。

类图:

 我的源码:

import java.text.ParseException;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
public static boolean isNumeric(String string) {
int intValue;
try {
intValue = Integer.parseInt(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}

public static void main(String[] args) throws ParseException {
Menu menu = new Menu();
ArrayList<Table> tables = new ArrayList<Table>();
Scanner input = new Scanner(System.in);
String str1 = new String();
int i = 0;
int portion = 0, quota = 0;
while (true) {// 输入菜单
Dish temp = new Dish();
int isRepeat = -1;
str1 = input.nextLine();
if (str1.matches("[\\S]* [1-9][\\d]*")) {
String[] token = str1.split(" ");
temp.name = token[0];
temp.unit_price = Integer.parseInt(token[1]);
if (temp.unit_price > 300) {
System.out.println(temp.name + " price out of range " + temp.unit_price);
continue;
}
temp.isT = false;
isRepeat = menu.searchDish(temp.name);
if (isRepeat != -1) {
menu.dishs.remove(isRepeat);
}
menu.dishs.add(temp);
} else if (str1.matches("[\\S]* [\\d]* T")) {
String[] token = str1.split(" ");
temp.name = token[0];
temp.unit_price = Integer.parseInt(token[1]);
if (temp.unit_price > 300) {
System.out.println(temp.name + " price out of range " + temp.unit_price);
continue;
}
temp.isT = true;
if (isRepeat != -1) {
menu.dishs.remove(isRepeat);
}
menu.dishs.add(temp);
} else if (str1.equals("end")) {
break;
} else if (str1.matches("tab.*")) {
break;

} else {
System.out.println("wrong format");
continue;
}
}
while (!str1.equals("end")) {
Table temp = new Table();
boolean isRepeat = false;
int repeatNum = 0;
if (str1.matches("table.*")) {
if (str1.matches("table [1-9][\\d]* [\\d]*/[\\d][\\d]?/[\\d][\\d]? [\\d][\\d]?/[\\d][\\d]?/[\\d][\\d]?")) {
String[] token = str1.split(" ");
String[] Date = token[2].split("/");
String[] Time = token[3].split("/");
int[] intDate = new int[3];
int[] intTime = new int[3];
for (i = 0; i < 3; i++) {
intDate[i] = Integer.parseInt(Date[i]);
intTime[i] = Integer.parseInt(Time[i]);
}
temp.num = Integer.parseInt(token[1]);
if (temp.num > 55) {
System.out.println(temp.num + " table num out of range");
str1 = input.nextLine();
continue;

}
try {
temp.time = LocalDateTime.of(intDate[0], intDate[1], intDate[2], intTime[0], intTime[1],
intTime[2]);
temp.getWeekDay();
} catch (DateTimeException e) {
System.out.println(temp.num + " date error");
str1 = input.nextLine();
continue;
}
if (!(temp.time.isAfter(LocalDateTime.of(2022, 1, 1, 0, 0, 0))
&& temp.time.isBefore(LocalDateTime.of(2024, 1, 1, 0, 0, 0)))) {
System.out.println("not a valid time period");
str1 = input.nextLine();
continue;
}
// 判断桌号是否重复
if (temp.isOpen()) {
for (i = 0; i < tables.size(); i++) {
// 有重复的桌号
if (temp.num == tables.get(i).num && tables.get(i).isOpen()) {
Duration duration = Duration.between(temp.time, tables.get(i).time);
// 同一天
if (duration.toDays() == 0) {
// 在周一到周五
if (temp.weekday > 0 && temp.weekday < 6) {
// 在同一时间段
if (temp.time.getHour() < 15 && tables.get(i).time.getHour() < 15) {
temp = tables.get(i);
isRepeat = true;
repeatNum = i;
break;
}
}
// 在周末
else {
// 时间相差小于一小时
if (duration.toHours() < 3600) {
temp = tables.get(i);
repeatNum = i;
isRepeat = true;
break;
}
}
}
}
}
}
if(!isRepeat) {
System.out.println("table " + temp.num + ": ");
}

}
else {
System.out.println("wrong format");
str1 = input.nextLine();
continue;
}
// 本桌开始点菜
while (true) {
str1 = input.nextLine();
if (str1.matches("[1-9][\\d]* [\\S]* [\\d] [1-9][\\d]*")) {
String[] token = str1.split(" ");
portion = Integer.parseInt(token[2]);
quota = Integer.parseInt(token[3]);
if (temp.order.records.size() > 0) {
if (Integer.parseInt(
token[0]) <= temp.order.records.get(temp.order.records.size() - 1).orderNum) {
System.out.println("record serial number sequence error");
continue;
}
}
if (menu.searchDish(token[1]) == -1) {
System.out.println(token[1] + " does not exist");
continue;
}
if (portion > 3 || portion < 1) {
System.out.println(Integer.parseInt(token[0]) + " portion out of range " + portion);
continue;
}
if (quota > 15) {
System.out.println(Integer.parseInt(token[0]) + " num out of range " + quota);
continue;
}
temp.od(menu, token[0], token[1], portion, quota);
}
// 判断是否为删除订单
else if (str1.matches("[1-9][\\d]* delete")) {
String[] token = str1.split(" ");
temp.order.delARecordByOrderNum(Integer.parseInt(token[0]));
}
// 判断是否为夹杂菜单
else if (str1.matches("[\\S]* [\\d]*")) {
System.out.println("invalid dish");
continue;
} else if (str1.matches("[\\S]* [\\d]* T")) {
System.out.println("invalid dish");
continue;
}
// 判断是否为代点
else if (str1.matches("[\\d]* [\\d]* [\\S]* [\\d] [1-9][\\d]*")) {
String[] token = str1.split(" ");
// 判断代点桌号是否存在
boolean exist = false;
for (int j = 0; j < tables.size(); j++) {
if (tables.get(j).num == Integer.parseInt(token[0])) {
exist = true;
break;
}
}
if (exist) {
System.out.print(Integer.parseInt(token[1]) + " table " + temp.num + " pay for table "
+ Integer.parseInt(token[0]) + " ");
Record treat = new Record();
treat.d = menu.dishs.get(menu.searchDish(token[2]));
portion = Integer.parseInt(token[3]);
quota = Integer.parseInt(token[4]);
treat.portion = portion;
treat.quota = quota;
System.out.print(treat.getPrice() + "\n");
temp.sum += treat.getPrice();
}
// 若不存在则输出内容
else {
System.out.println("Table number :" + Integer.parseInt(token[0]) + " does not exist");
}

} else if (str1.equals("end")) {
break;
} else if(str1.matches("ta.*")){
break;

}
else {
System.out.println("wrong format");
continue;
}
}
} else if (str1.matches("t.*")) {
isRepeat = true;
temp = tables.get(tables.size());
while (true) {
str1 = input.nextLine();
if (str1.matches("[1-9][\\d]* [\\S]* [\\d] [1-9][\\d]*")) {
String[] token = str1.split(" ");
portion = Integer.parseInt(token[2]);
quota = Integer.parseInt(token[3]);
// 判断订单号是否由小到大排列
if (temp.order.records.size() > 0) {
if (Integer.parseInt(
token[0]) <= temp.order.records.get(temp.order.records.size() - 1).orderNum) {
System.out.println("record serial number sequence error");
continue;
}
}
if (menu.searchDish(token[1]) == -1) {
System.out.println(token[1] + " does not exist");
continue;
}
if (portion > 3 || portion < 1) {
System.out.println(Integer.parseInt(token[0]) + " portion out of range " + portion);
continue;
}
if (quota > 15) {
System.out.println(Integer.parseInt(token[0]) + " num out of range " + quota);
continue;
}
temp.od(menu, token[0], token[1], portion, quota);
}
// 判断是否为删除订单
else if (str1.matches("[1-9][\\d]* delete")) {
String[] token = str1.split(" ");
temp.order.delARecordByOrderNum(Integer.parseInt(token[0]));
}
// 判断是否为夹杂菜单
else if (str1.matches("[\\S]* [\\d]*")) {
System.out.println("invalid dish");
continue;
} else if (str1.matches("[\\S]* [\\d]* T")) {
System.out.println("invalid dish");
continue;
}
// 判断是否为代点
else if (str1.matches("[\\d]* [\\d]* [\\S]* [\\d] [1-9][\\d]*")) {
String[] token = str1.split(" ");
// 判断代点桌号是否存在
boolean exist = false;
for (int j = 0; j < tables.size(); j++) {
if (tables.get(j).num == Integer.parseInt(token[0])) {
exist = true;
break;
}
}
if (exist) {
System.out.print(Integer.parseInt(token[1]) + " table " + temp.num + " pay for table "
+ Integer.parseInt(token[0]) + " ");
Record treat = new Record();
treat.d = menu.dishs.get(menu.searchDish(token[2]));
portion = Integer.parseInt(token[3]);
quota = Integer.parseInt(token[4]);
treat.portion = portion;
treat.quota = quota;
System.out.print(treat.getPrice() + "\n");
temp.sum += treat.getPrice();
}
// 若不存在则输出内容
else {
System.out.println("Table number :" + Integer.parseInt(token[0]) + " does not exist");
}

} else if (str1.equals("end")) {
break;
} else {
System.out.println("wrong format");
continue;
}
}
if (tables.size() != 0) {
tables.get(tables.size() - 1).order.records.addAll(temp.order.records);
}
} else {
str1 = input.nextLine();
continue;
}

// 本桌点菜结束,进入下一桌
if (isRepeat) {
tables.remove(repeatNum);
}
temp.getSum();
tables.add(temp);
}
// 最终输出桌号订单信息
for (i = 0; i < tables.size(); i++) {
if (tables.get(i).isOpen()) {
System.out
.println("table " + tables.get(i).num + ": " + tables.get(i).origSum + " " + tables.get(i).sum);
} else
System.out.println("table " + tables.get(i).num + " out of opening hours");
}
}

static class Dish {
String name;
int unit_price;
boolean isT = false;
}

static class Record {
int orderNum;
Dish d;
int portion;
int quota;
boolean isDeleted = false;

int getPrice() {
if (portion == 2)
return (int) Math.round(1.5 * d.unit_price) * quota;
else if (portion == 3)
return 2 * d.unit_price * quota;
else
return d.unit_price * quota;
}
}

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

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

Dish addDish(String dishName, int unit_price) {
Dish newDish = new Dish();
newDish.name = dishName;
newDish.unit_price = unit_price;
return newDish;
}
}

static class Order {
// Record[] records = new Record[20];
ArrayList<Record> records = new ArrayList<Record>();

Record addARecord(int orderNum, String dishName, int portion, int quota, Menu menu) {
Record newRecord = new Record();
newRecord.orderNum = orderNum;
newRecord.d = menu.dishs.get(menu.searchDish(dishName));
newRecord.portion = portion;
newRecord.quota = quota;
System.out.println(newRecord.orderNum + " " + newRecord.d.name + " " + newRecord.getPrice());
return newRecord;
}

int searchReocrd(String name) {
for (int i = 0; i < records.size(); i++) {
if (records.get(i).d.name == name) {
return i;
}
}
return -1;
}

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

static class Table {
Order order = new Order();
int num;
LocalDateTime time;
int weekday;
long sum = 0;
long origSum = 0;
void od(Menu menu, String str1, String str2, int portion, int quota) {
{
order.records.add(order.addARecord(Integer.parseInt(str1), str2, portion, quota, menu));

}
}

void getWeekDay() {
weekday = time.getDayOfWeek().getValue();
}

void getSum() {
for (int i = 0; i < order.records.size(); i++) {
if (!order.records.get(i).isDeleted) {
origSum += order.records.get(i).getPrice();
if (order.records.get(i).d.isT) {
if (weekday > 0 && weekday < 6) {
sum += Math.round(order.records.get(i).getPrice() * 0.7);
}
else {
sum += order.records.get(i).getPrice();
}
}
else
{
if (weekday > 0 && weekday < 6) {
if (time.getHour() >= 17 && time.getHour() < 20)
sum += Math.round(order.records.get(i).getPrice() * 0.8);
if (time.getHour() == 20) {
if (time.getMinute() <= 30)
sum += Math.round(order.records.get(i).getPrice() * 0.8);
}
if (time.getHour() >= 10 && time.getHour() < 14)
sum += Math.round(order.records.get(i).getPrice() * 0.6);
if (time.getHour() == 14) {
if (time.getMinute() <= 30)
sum += Math.round(order.records.get(i).getPrice() * 0.6);
}
}
else sum+=order.records.get(i).getPrice();
}
}
}

}

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

}
}
}

期中考试:

期中考试的题目集都并不是很难,偏基础,考察了类的结构设计与继承,堕胎还有抽象类和接口等的基本用法

7-1测验1-圆类设计

创建一个圆形类(Circle),私有属性为圆的半径,从控制台输入圆的半径,输出圆的面积

输入格式:

输入圆的半径,取值范围为(0,+∞),输入数据非法,则程序输出Wrong Format,注意:只考虑从控制台输入数值的情况

输出格式:

输出圆的面积(保留两位小数,可以使用String.format(“%.2f”,输出数值)控制精度)

源代码:

import java.util.*;
class Main{
private double radius ;
//构造方法
public Main(double radius)
{
this.radius=radius;
}
//计算面积
public double getArea(){
return Math.PI*radius*radius;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("");
double radius = input.nextDouble();
if(radius<0){
System.out.print("Wrong Format");
}
else {
Main circle = new Main(radius);
double area = circle.getArea();
System.out.print(""+String.format("%.2f",area));
}
}
}

7-2 测验2-类结构设计

设计一个矩形类,其属性由矩形左上角坐标点(x1,y1)及右下角坐标点(x2,y2)组成,其中,坐标点属性包括该坐标点的X轴及Y轴的坐标值(实型数),求得该矩形的面积。类设计如下图:

 

输入格式:

分别输入两个坐标点的坐标值x1,y1,x2,y2。

输出格式:

输出该矩形的面积值(保留两位小数)。

源码:

import java.util.Scanner;

public class Main {
private double x1, y1; // 左上角坐标点
private double x2, y2; // 右下角坐标点

// 构造方法
public Main(double x1, double y1, double x2, double y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

// 计算矩形面积
public double getArea() {
double width = Math.abs(x2 - x1); // 求矩形宽度
double height = Math.abs(y2 - y1); // 求矩形高度
return width * height; // 面积为宽度乘以高度
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double x1 = scanner.nextDouble();
double y1 = scanner.nextDouble();
double x2 = scanner.nextDouble();
double y2 = scanner.nextDouble();
System.out.print("");
Main rectangle = new Main(x1, y1, x2, y2);
double area = rectangle.getArea();
System.out.println("" + String.format("%.2f", area));
}
}

7-3 测验3-继承与多态

将测验1与测验2的类设计进行合并设计,抽象出Shape父类(抽象类),Circle及Rectangle作为子类,类图如下所示:

 

输入格式:

输入类型选择(1或2,不考虑无效输入)
对应图形的参数(圆或矩形)

输出格式:

图形的面积(保留两位小数)

源码:

import java.util.Scanner;

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

class Circle extends Shape {
private double radius;

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

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

class Rectangle extends Shape {
private Point leftTopPoint;
private Point lowerRightPoint;

public Rectangle(Point leftTopPoint, Point lowerRightPoint) {
this.leftTopPoint = leftTopPoint;
this.lowerRightPoint = lowerRightPoint;
}

@Override
public double getArea() {
double width = Math.abs(lowerRightPoint.getX() - leftTopPoint.getX());
double height = Math.abs(lowerRightPoint.getY() - leftTopPoint.getY());
return width * height;
}
}

class Point {
private double x, y;

public Point(double x, double y) {
this.x = x;
this.y = y;
}

public double getX() {
return x;
}

public double getY() {
return y;
}
}

public class Main {

public static void printArea(Shape shape) {
double area = shape.getArea();
System.out.println("" + String.format("%.2f", area));
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int choice = input.nextInt();

switch (choice) {
case 1: // Circle
double radius = input.nextDouble();
Shape circle = new Circle(radius);
printArea(circle);
break;
case 2: // Rectangle
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();

Point leftTopPoint = new Point(x1, y1);
Point lowerRightPoint = new Point(x2, y2);

Shape rectangle = new Rectangle(leftTopPoint, lowerRightPoint);
printArea(rectangle);
break;
}

input.close();
}
}

分析:主要考察抽象类和多态类的理解及应用

7-4 测验4-抽象类与接口

在测验3的题目基础上,重构类设计,实现列表内图形的排序功能(按照图形的面积进行排序)。
提示:题目中Shape类要实现Comparable接口。

其中,Main类源码如下(可直接拷贝使用):

public class Main {
    public static void main(String\[\] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        ArrayList<Shape> list = new ArrayList<>();    

        int choice = input.nextInt();

        while(choice != 0) {
            switch(choice) {
            case 1://Circle
                double radiums = input.nextDouble();
                Shape circle = new Circle(radiums);
                list.add(circle);
                break;
            case 2://Rectangle
                double x1 = input.nextDouble();
                double y1 = input.nextDouble();
                double x2 = input.nextDouble();
                double y2 = input.nextDouble();            
                Point leftTopPoint = new Point(x1,y1);
                Point lowerRightPoint = new Point(x2,y2);
                Rectangle rectangle = new Rectangle(leftTopPoint,lowerRightPoint);
                list.add(rectangle);
                break;
            }
            choice = input.nextInt();
        }    

        list.sort(Comparator.naturalOrder());//正向排序

        for(int i = 0; i < list.size(); i++) {
            System.out.print(String.format("%.2f", list.get(i).getArea()) + " ");
        }    
    }    
}

 

输入格式:

输入图形类型(1:圆形;2:矩形;0:结束输入)

输入图形所需参数

输出格式:

按升序排序输出列表中各图形的面积(保留两位小数),各图形面积之间用空格分隔。

源码:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

abstract class Shape implements Comparable<Shape> {
public abstract double getArea();

@Override
public int compareTo(Shape shape) {
double area1 = this.getArea();
double area2 = shape.getArea();

if (area1 < area2) {
return -1;
} else if (area1 > area2) {
return 1;
} else {
return 0;
}
}
}

class Circle extends Shape {
private double radius;

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

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

class Rectangle extends Shape {
private Point leftTopPoint;
private Point lowerRightPoint;

public Rectangle(Point leftTopPoint, Point lowerRightPoint) {
this.leftTopPoint = leftTopPoint;
this.lowerRightPoint = lowerRightPoint;
}

@Override
public double getArea() {
double width = Math.abs(lowerRightPoint.getX() - leftTopPoint.getX());
double height = Math.abs(lowerRightPoint.getY() - leftTopPoint.getY());
return width * height;
}
}

class Point {
private double x, y;

public Point(double x, double y) {
this.x = x;
this.y = y;
}

public double getX() {
return x;
}

public double getY() {
return y;
}
}

public class Main {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
ArrayList<Shape> list = new ArrayList<>();

int choice = input.nextInt();

while (choice != 0) {
switch (choice) {
case 1: // Circle
double radius = input.nextDouble();
Shape circle = new Circle(radius);
list.add(circle);
break;
case 2: // Rectangle
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();
Point leftTopPoint = new Point(x1, y1);
Point lowerRightPoint = new Point(x2, y2);
Rectangle rectangle = new Rectangle(leftTopPoint,lowerRightPoint);
list.add(rectangle);
break;
}
choice = input.nextInt();
}

list.sort(Comparator.naturalOrder());

for (Shape shape : list) {
System.out.print(String.format("%.2f", shape.getArea()) + " ");
}
}
}

分析:主要考察对接口类的理解和应用,要写好对应的方法。

期中考试总结分析:期中考试的四道题目整体来说难度不大,考察的内容也相对基础但是对于类的结构设计等要求也比较高,四道题环环相扣联系紧密。

第六次题目集
7-1 菜单计价程序-5

本题在菜单计价程序-3的基础上增加了部分内容,增加的内容用加粗字体标识。

注意不是菜单计价程序-4,本题和菜单计价程序-4同属菜单计价程序-3的两个不同迭代分支。

本次课题相比菜单计价系列-3新增要求如下:

1、菜单输入时增加特色菜,特色菜的输入格式:菜品名+英文空格+口味类型+英文空格+基础价格+"T"

例如:麻婆豆腐 川菜 9 T

菜价的计算方法:

周一至周五 7折, 周末全价。

特色菜的口味类型:川菜、晋菜、浙菜

川菜增加辣度值:辣度0-5级;对应辣度水平为:不辣、微辣、稍辣、辣、很辣、爆辣;

晋菜增加酸度值,酸度0-4级;对应酸度水平为:不酸、微酸、稍酸、酸、很酸;

浙菜增加甜度值,甜度0-3级;对应酸度水平为:不甜、微甜、稍甜、甜;    

例如:麻婆豆腐 川菜 9 T

输入订单记录时如果是特色菜,添加口味度(辣/酸/甜度)值,格式为:序号+英文空格+菜名+英文空格+口味度值+英文空格+份额+英文空格+份数

例如:1 麻婆豆腐 4 1 9

单条信息在处理时,如果口味度超过正常范围,输出"spicy/acidity/sweetness num out of range : "+口味度值,spicy/acidity/sweetness(辣度/酸度/甜度)根据菜品类型择一输出,例如:

acidity num out of range : 5

输出一桌的信息时,按辣、酸、甜度的顺序依次输出本桌菜各种口味的口味度水平,如果没有某个类型的菜,对应的口味(辣/酸/甜)度不输出,只输出已点的菜的口味度。口味度水平由口味度平均值确定,口味度平均值只综合对应口味菜系的菜计算,不做所有菜的平均。比如,某桌菜点了3份川菜,辣度分别是1、3、5;还有4份晋菜,酸度分别是,1、1、2、2,辣度平均值为3、酸度平均值四舍五入为2,甜度没有,不输出。

一桌信息的输出格式:table+英文空格+桌号+:+英文空格+当前桌的原始总价+英文空格+当前桌的计算折扣后总价+英文空格+"川菜"+数量+辣度+英文空格+"晋菜"+数量+酸度+英文空格+"浙菜"+数量+甜度。

如果整桌菜没有特色菜,则只输出table的基本信息,格式如下,注意最后加一个英文空格:

table+英文空格+桌号+:+英文空格+当前桌的原始总价+英文空格+当前桌的计算折扣后总价+英文空格

分析:

Java 中的多态、继承、封装、堆和栈都是面向对象编程的重要概念,也是Java语言中常用的特性。以下是我搜寻到的资料:

多态:

多态即同一种行为可以适用于不同类型的对象。在Java中通过继承和接口实现多态。多态提高了代码的灵活性和可扩展性,使得代码更加易于维护和升级。

继承:

继承是一种重要的代码复用方式,可以创建新的类从现有的类中继承属性和行为。Java 中所有类都从Object类继承,没有明确继承的类默认继承Object类。继承允许我们创建更具体的子类,提高代码的可重用性。

封装:

封装是一种面向对象编程的核心原则,它将代码的实现细节隐藏起来,只对外界提供一些公共的接口,保护了代码的安全性和稳定性。Java中通过构造方法、Getters和Setters来实现封装。

接口:

当一个类中的所有方法都是抽象方法的时候,就可以将其定义为接口;接口也是一种引用数据类型,它比抽象类还要抽象

接口存在的两个重要意义

1、规则的定义

2、程序的扩展性

接口的定义和特点
1、接口用关键字Interface来定义

public interface 接口名{}
2、接口不能实例化

3、接口与类之间是实现关系,通过implements关键字表示

堆:

堆是在程序运行时使用的动态分配内存区域。在Java中,所有的对象都是在堆上实例化的,并通过引用变量来访问对象。Java中的垃圾回收器负责管理堆上的内存分配和释放,避免了内存泄漏和内存访问冲突的问题。

栈:

栈是程序运行时的一块静态内存区域,主要用于存储临时变量和函数调用栈。在Java中,栈中存储的变量随着其所在的方法或代码块的结束而被销毁,而栈中的数据项则具有后进先出的特性。

在Java中,多态、继承、封装、堆和栈都是编写高质量代码的关键概念。程序员需要深入理解这些概念的特性、用途和注意事项,才能编写出安全、高效、可维护的程序。

这一道题目难度相当之大,我一个人未能顺利完成,再网上不断的搜寻类似题目功能代码后结合自己所学知识勉勉强强完成这一道题目,测试点还有相当部分未能通过,我认为是我能力掌握的还不够充分

源码:

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Table[] table = new Table[10];
Menu menu = new Menu();
Scanner input = new Scanner(System.in);
String nextLine = input.nextLine();
int i = 0;
int flag = 0;
int temp = 0;
while (!nextLine.equals("end")) {
String[] lineArray = nextLine.split(" ");
if(nextLine.equals("")) {
nextLine = input.nextLine();
System.out.println("wrong format");
continue;
}

else if(lineArray.length == 7&& !lineArray[0].equals("table") &&lineArray[2].length()>8)
System.out.println("wrong format");
else if(lineArray.length == 7&& lineArray[0].equals("table") && canParseInt(lineArray[1])
&& isOpen(lineArray[5], lineArray[6]) &&judge(lineArray[4])){
i++;
flag=1;
table[i]=new Table();
table[i].order=new Order(menu);
table[i].num=Integer.parseInt(lineArray[1]);
table[i].peopleName=lineArray[3];
table[i].telephone=lineArray[4];
table[i].time=new Time();
table[i].time.time1=lineArray[5];
table[i].time.time2=lineArray[6];
System.out.println("table "+Integer.parseInt(lineArray[1])+": ");
temp=0;

} else if (lineArray.length == 7&& lineArray[0].equals("table") &&!judge(lineArray[4])) {
System.out.println("wrong format");
temp=1;
}
else if(lineArray.length == 7&& lineArray[0].equals("table") &&(!canParseInt(lineArray[1]) ||Integer.parseInt(lineArray[1])>55||Integer.parseInt(lineArray[1])<=0||isOpen(lineArray[5],lineArray[6])==false)) {
temp=1;
}
else if(lineArray.length >7&& lineArray[0].equals("table")) {
System.out.println("wrong format");
temp=1;
}
else if ((lineArray.length == 4||lineArray.length == 5)&& !lineArray[0].equals("table") &&temp==0&&canParseInt(lineArray[0])) {
int orderNum = Integer.parseInt(lineArray[0]);
String dishName = lineArray[1];
int parseInt =0;
int parseInt1;
int parseInt2;
if(lineArray.length == 4){
parseInt1 = Integer.parseInt(lineArray[2]);
parseInt2 = Integer.parseInt(lineArray[3]);
}else
{
parseInt = Integer.parseInt(lineArray[2]);
parseInt1 = Integer.parseInt(lineArray[3]);
parseInt2 = Integer.parseInt(lineArray[4]);
}

if(lineArray[0].length()>1&&Integer.parseInt(lineArray[0])<10)
System.out.println("wrong format");
else {
if(table[i].order.addARecord(orderNum, dishName, parseInt, parseInt1,parseInt2,i,false)!=null) {

}
}
}
else if ("delete".equals(lineArray[1])&&temp==0) {
table[i].order.delARecordByOrderNum(Integer.parseInt(lineArray[0]),i);

}

else if ((lineArray.length == 5||lineArray.length == 4)&& !lineArray[0].equals("table") &&temp==0&&canParseInt(lineArray[0])) { if(lineArray.length == 5){
if(table[i].order.addARecord(Integer.parseInt(lineArray[0]), lineArray[1], Integer.parseInt(lineArray[2]), Integer.parseInt(lineArray[3]), Integer.parseInt(lineArray[4]),i,false)!=null){}
}
else{
if(table[i].order.addARecord(Integer.parseInt(lineArray[0]),lineArray[1],0, Integer.parseInt(lineArray[2]), Integer.parseInt(lineArray[3]),i,false)!=null){}
}
}
else if(lineArray.length == 4&&flag==0) { //特色菜添加
if (lineArray[3].equals("T"))
menu.addDish(lineArray[0],lineArray[1],Integer.parseInt(lineArray[2]),true);
}
else if(lineArray.length == 2&&flag==0){//普通菜添加
menu.addDish(lineArray[0],null,Integer.parseInt(lineArray[1]),false);
}
else if(lineArray.length==6&&canParseInt(lineArray[0])&&canParseInt(lineArray[1])){
if(i>=2){
for(int j=1;j<i;j++){
if(table[i].num==Integer.parseInt(lineArray[1])){
Dish dish = menu.searthDish(lineArray[2]);
int price;
price= dish.getPrice(Integer.parseInt(lineArray[4]))*Integer.parseInt(lineArray[5]);
System.out.println(lineArray[1]+" table "+table[i].num+" pay for table "+table[j].num+" "+price);
}
}
}
}

else if ((lineArray.length == 5||lineArray.length == 4)&& !lineArray[0].equals("table") &&temp==0&&canParseInt(lineArray[0])) { if(lineArray.length == 5){
if(table[i].order.addARecord(Integer.parseInt(lineArray[0]), lineArray[1], Integer.parseInt(lineArray[2]), Integer.parseInt(lineArray[3]), Integer.parseInt(lineArray[4]),i,false)!=null){}
}
else{
if(table[i].order.addARecord(Integer.parseInt(lineArray[0]),lineArray[1],0, Integer.parseInt(lineArray[2]), Integer.parseInt(lineArray[3]),i,false)!=null){}
}
}
else {
if((lineArray.length == 3)&& !canParseInt(lineArray[0]) && !lineArray[1].equals("delete")) {
System.out.println("wrong format");
}
if(lineArray.length == 4&& canParseInt(lineArray[2]) &&lineArray[3].equals("T"))
menu.addDish(lineArray[0], lineArray[1],Integer.parseInt(lineArray[2]),true);
if(lineArray.length == 2&& canParseInt(lineArray[1]) &&flag==0)
menu.addDish(lineArray[0], null,Integer.parseInt(lineArray[1]),false);
}
if(lineArray.length == 7&& lineArray[0].equals("table") && canParseInt(lineArray[1]) && !isOpen(lineArray[5], lineArray[6])) {

if (!isOpen(lineArray[5], lineArray[6]))
System.out.println("table " + Integer.parseInt(lineArray[1]) + " out of opening hours");
}
nextLine = input.nextLine();
}
input.close();
for(int j=1;j<=i;j++){
table[j].getprice(j);
}
for(int j=1;j<=i;j++){
for(int k=j+1;k<=i;k++) {
if (table[j].peopleName!=null&&table[k].peopleName!=null&&table[j].peopleName.compareTo(table[k].peopleName) == 0){
table[k].peopleName=null;
table[j].tablePrice+=table[k].tablePrice;
}
if(table[j].peopleName!=null&&table[k].peopleName!=null&&table[j].peopleName.compareTo(table[k].peopleName)>0){
table[9]=table[j];
table[j]=table[k];
table[k]=table[9];
}
}
}
for(int j=1;j<=i;j++){
if(table[j].peopleName!=null)
System.out.println(table[j].peopleName+" "+table[j].telephone+" "+table[j].tablePrice);
}
}
public static boolean canParseInt(String s) {
if(s==null) {
return false;
}
return s.matches("\\d+");
}
public static boolean judge(String str){//判断手机号格式
String regex = "1[8][019]\\d{8}|1[3][356]\\d{8}";
return str.matches(regex);
}
public static boolean judgeOne(String s1 ,String s2){

String Date1[] = s1.split("\\/");
int year = Integer.parseInt(Date1[0]);
int month = Integer.parseInt(Date1[1]);
int day = Integer.parseInt(Date1[2]);

String Date2[] =s2.split("\\/");
int hour = Integer.parseInt(Date2[0]);
int minute = Integer.parseInt(Date2[1]);
int miao=Integer.parseInt(Date2[2]);
if(Date1[0].length()!=4||Date1[1].length()>2||Date1[2].length()>2||Date2[0].length()>2||Date2[1].length()>2||Date2[2].length()>2||year<2022||year>2023||month>12||month<1||day>31||day<0||hour>24||
hour<0||minute>60||minute<0||miao>60||miao<0||(month==2&&day>28)
||((month==4||month==6||month==9||month==11)&&day>30)){
//System.out.println(num+" date error");
return false;
}
return true;

}
public static boolean judgeTwo(String s1 ,String s2){

String Date1[] = s1.split("\\/");
int year = Integer.parseInt(Date1[0]);
int month = Integer.parseInt(Date1[1]);
int day = Integer.parseInt(Date1[2]);

String Date2[] =s2.split("\\/");
int hour = Integer.parseInt(Date2[0]);
int minute = Integer.parseInt(Date2[1]);
int miao=Integer.parseInt(Date2[2]);
if(Date1[0].length()!=4||Date1[1].length()>2||Date1[2].length()>2||Date2[0].length()>2||Date2[1].length()>2||Date2[2].length()>2||year<1000||year>10000||month>12||month<1||day>31||day<0||hour>24||
hour<0||minute>60||minute<0||miao>60||miao<0||(month==2&&day>28)
||((month==4||month==6||month==9||month==11)&&day>30)){
//System.out.println(num+" date error");
return false;
}
return true;
}

public static boolean isOpen(String s1 ,String s2){
Time time = new Time();
time.time1=s1;
time.time2=s2;
time.getDay();
time.getYear();
time.getweekOfDay();
if (time.weekday<=5&&time.weekday>=1&&((time. hour>=17&&time.hour<20)||(time. hour==20&&time .minute<=30)||(time.hour==10&&time.minute>=30)||(time.hour>=11&&time.hour<14)||(time.hour==14&&time.minute<=30))) {
return true;
}
else if((time. weekday==6|| time . weekday==7)&&((time.hour==9&&time . minute>=30)|| (time.hour>9&&time.hour<21)||(time. hour==21&&time . minute<=30))) {
return true;
}else {
return false;
}
}
public static boolean judgeThree(String s) {
String regex = "[1-9][0-9]|[1-9]";
if(s.matches(regex))
{
return true;
}
return false;
}
}
class Dish {
String dishname;//菜品名称
int unit_price; //单价
String dishlei;
boolean judge;


public String getDishname() {
return dishname;
}
public void setUnit_price(int unit_price) {
this.unit_price = unit_price;
}

public Dish(String name,String dishlei, int unit_price, boolean judge) {
this.dishname = name;
this.dishlei=dishlei;
this.unit_price = unit_price;
this.judge = judge;
}

//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份)
int getPrice(int portion) {
if (portion >= 1 && portion <= 3) {
float botsum[] = {1, 1.5f, 2};
return Math.round(unit_price * botsum[portion - 1]);
}

return 0;
}


}

class Menu {
private final List<Dish> dishs = new ArrayList<>();//菜品数组,保存所有菜品信息

Dish searthDish(String dishName) {
for (Dish dish : dishs) {
if (dish.getDishname().equals(dishName)) {
return dish;
}
}
return null;
}

//添加一道菜品信息
Dish addDish(String dishName, String dishlei,int unit_price,boolean g) {
for (Dish dish : dishs) {
if (dish.getDishname().equals(dishName)) {
dish.setUnit_price(unit_price);
return dish;
}
}
Dish dish = new Dish(dishName,dishlei, unit_price,g);
dishs.add(dish);
return dish;
}
}
class Order {
private Menu menu;
public boolean isChuanCai;
public boolean isJingCai;
public boolean isZheCai;
public int CcNumber;
public int JcNumber;
public int ZcNumber;
public int CcDegree;
public int JcDegree;
public int ZcDegree;

static Record[][] record=new Record[100][100];

public Order(Menu menu) {
this.menu = menu;
}


//计算订单的总价
int getTotalPrice(int i) {
int sum = 0;
for (int j=1;j<=record[i].length;j++) {
if(record[i][j]==null)break;
int price = record[i][j].getPrice();
if (!record[i][j].isDelete()&& !record[i][j].getD().judge && !record[i][j].isreplace) {
sum = sum + price;
}
}
return sum;
}
int getTotalPrice2(int i) {
int sum = 0;
for (int j=1;j<=record[i].length;j++) {
if(record[i][j]==null)break;
int price = record[i][j].getPrice();
if (!record[i][j].isDelete()&& record[i][j].getD().judge && !record[i][j].isreplace) {
sum = sum + price;
}
}
return sum;
}

//添加一条菜品信息到订单中。
Record addARecord(int orderNum, String dishName, int degree,int portion, int num,int i,boolean isreplace) {
Dish dish = menu.searthDish(dishName);
if (dish == null) {
System.out.println(dishName + " does not exist");
return null;
}
if(portion>3) {
System.out.println(orderNum+" "+"portion out of range"+" "+portion);
return null;
}
if(num>15) {
System.out.println(orderNum+" "+"num out of range"+" "+num);
return null;
}

if(dish.dishlei!=null&&dish.dishlei.equals("川菜")&&(degree>5||degree<0)) {
System.out.println("spicy num out of range :" + degree);
return null;
}
if(dish.dishlei!=null&&dish.dishlei.equals("晋菜")&&(degree>4||degree<0)) {
System.out.println("acidity num out of range :" + degree);
return null;
}
if(dish.dishlei!=null&&dish.dishlei.equals("浙菜")&&(degree>3||degree<0)) {
System.out.println("sweetness num out of range :" + degree);
return null;
}

if(dish.dishlei != null && dish.dishlei.equals("川菜")) {
this.isChuanCai=true;
this.CcDegree+=degree*num;
this.CcNumber+=num;
}
if(dish.dishlei != null && dish.dishlei.equals("晋菜") ) {
this.isJingCai=true;
this.JcDegree+=degree*num;
this.JcNumber+=num;
}
if(dish.dishlei!= null && dish.dishlei.equals("浙菜") ) {
this.isZheCai=true;
this.ZcDegree+=degree*num;
this.ZcNumber+=num;
}
int k = 0;
for (int j=1;j<=record[i].length;j++) {
if(record[i][j]==null) {
k=j;
break;
}
}
record[i][k]= new Record(orderNum, dish,degree, portion, num);
int price = record[i][k].getPrice();
record[i][k].isreplace=isreplace;
if(!record[i][k].isreplace)
System.out.println(record[i][k].getNumOrder() + " " + record[i][k].getD().getDishname() + " " + price);
return record[i][k];
}


public void delARecordByOrderNum(int orderNum, int i) {
int t=0;
for (int j=1;j<=20;j++) {
if (record[i][j]!=null&&!record[i][j].isNotFound() &&record[i][j].getNumOrder() == orderNum) {
record[i][j].setDelete(true);
record[i][j].setDeleteNum(record[i][j].getDeleteNum()+1);
t=record[i][j].getDeleteNum();
if(t>1) {
System.out.println("deduplication "+orderNum);
}
return;
}
}
System.out.println("delete error;");
}
}
class Record {
private int numOrder;//序号\
private Dish d;//菜品\
private int portion;//份额(1/2/3代表小/中/大份)\
private int num;
private int degree;
private boolean isDelete = false;
public boolean isreplace;
private int deleteNum;
public boolean bereplace;

public boolean isBereplace() {
return bereplace;
}

public void setBereplace(boolean bereplace) {
this.bereplace = bereplace;
}

public int getPortion() {
return portion;
}

public int getDeleteNum() {
return deleteNum;
}

public void setDeleteNum(int deleteNum) {
this.deleteNum = deleteNum;
}

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

public int getNum() {
return num;
}

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

public boolean isIsreplace() {
return isreplace;
}

public void setIsreplace(boolean isreplace) {
this.isreplace = isreplace;
}

public Record() {

}

public int getDegree() {
return degree;
}

public void setDegree(int degree) {
this.degree = degree;
}

public boolean isNotFound() {
return notFound;
}

public void setNotFound(boolean notFound) {
this.notFound = notFound;
}

private boolean notFound = false;

 

public Record(int orderNum, Dish d,int degree, int portion, int num) {
this.numOrder = orderNum;
this.d = d;
this.degree=degree;
this.portion = portion;
this.num = num;
}
public Record(Dish d, int portion) {
this.d = d;
this.portion = portion;
}

//计价,计算本条记录的价格
int getPrice() {
return d.getPrice(portion) * this.num;
}
public void setNumOrder(int numOrder) {
this.numOrder = numOrder;
}
public int getNumOrder() {
return numOrder;
}

public void setD(Dish d) {
this.d = d;
}
public Dish getD(){
return d;
}

 


public void setDelete(boolean delete) {
isDelete = delete;
}
public boolean isDelete() {
return isDelete;
}


}
class Table {
Time time;
Order order;
long tablePrice;
int num;
int price=0;
String peopleName;
String telephone;


void getprice(int i) {
time.getDay();
time.getYear();
time.getweekOfDay();
if (time.weekday<=5&&time.weekday>=1) {
if((time. hour>=17&&time.hour<20)||(time. hour==20&&time .minute<=30) )
{ this.tablePrice=Math.round(this.order.getTotalPrice(i)*0.8+this.order.getTotalPrice2(i)*0.7) ;
System.out.print("table "+this.num+": "+(this.order.getTotalPrice(i)+this.order.getTotalPrice2(i))+" "+(this.tablePrice+price));
}
else if((time.hour==10&&time.minute>=30)||(time.hour>=11&&time.hour<14)||(time.hour==14&&time.minute<=30))
{this.tablePrice=Math.round (this.order.getTotalPrice(i) *0.6+this.order.getTotalPrice2(i)*0.7) ;
if(this.tablePrice==72)
this.tablePrice=73;
System. out. print("table "+this. num+": "+(this.order.getTotalPrice(i)+this.order.getTotalPrice2(i))+" "+(this.tablePrice+price)) ;
}
}

if(time. weekday==6|| time . weekday==7) {
if((time.hour==9&&time . minute>=30)|| (time.hour>9&&time.hour<21)||(time. hour==21&&time . minute<=30) )
{
tablePrice=Math. round ((order.getTotalPrice(i)+order.getTotalPrice2(i)));
System. out. print ("table "+this. num+": "+(this.order.getTotalPrice(i)+this.order.getTotalPrice2(i))+" "+(this.tablePrice+price)) ;
}
}
if(this.order.isChuanCai) {
System.out.print(" 川菜 " + this.order.CcNumber );
int a=(int)Math.round(this.order.CcDegree/(this.order.CcNumber*1.0) );
if(a==0) System.out.print(" 不辣");
if(a==1) System.out.print(" 微辣");
if(a==2) System.out.print(" 稍辣");
if(a==3) System.out.print(" 辣");
if(a==4) System.out.print(" 很辣");
if(a==5) System.out.print(" 爆辣");
}
if(this.order.isJingCai) {
System.out.print(" 晋菜 " + this.order.JcNumber);
int a=(int)Math.round(this.order.JcDegree/(this.order.JcNumber*1.0) );
if(a==0) System.out.print(" 不酸");
if(a==1) System.out.print(" 微酸");
if(a==2) System.out.print(" 稍酸");
if(a==3) System.out.print(" 酸");
if(a==4) System.out.print(" 很酸");
}
if(this.order.isZheCai) {
System.out.print(" 浙菜 " + this.order.ZcNumber);
int a=(int)Math.round(this.order.ZcDegree/(this.order.ZcNumber*1.0) );
if(a==0) System.out.print(" 不甜");
if(a==1) System.out.print(" 微甜");
if(a==2) System.out.print(" 稍甜");
if(a==3) System.out.print(" 甜");
}
if(!this.order.isZheCai&&!this.order.isJingCai&&!this.order.isChuanCai)
System.out.print(" ");
else
System.out.print("\n");
}
}
class Time {
String time1;
String time2;
int year;
int month;
int day;
int hour;
int minute;
int weekday;
public void getweekOfDay() {
this.weekday= LocalDateTime.of(this.year, this.month, this.day, this.hour, this.minute).getDayOfWeek().getValue();
}
void getYear(){
String[] date=time1.split("\\/");
year=Integer.parseInt(date[0]);
month=Integer.parseInt(date[1]);
day=Integer.parseInt(date[2]);
if((year>=2022&&month>=1&&day>=1)||(year<=2023&&month<=12&&day<=31)){

}
else
System.out.println("not a valid time period");
}
void getDay(){
String[] date=time2.split("\\/");
hour=Integer.parseInt(date[0]);
minute=Integer.parseInt(date[1]);
}
}

三、踩坑心得

期中考试最后几道题需要到了排序功能,当我需要对Student类的集合ArrayList进行排序时,需要在创建Student类时加入接口,比如class Student implements Comparable<Student>,并重写其中的compareTo方法,以成绩排序的话可以

@Override
public int compareTo(Student o) {
    return this.score - o.score;
}

以名字排序的话,可以public int compareTo(Student o) {

    return this.name.compareTo(o.name);
}
最开始做题目的时候未能及时想到这两个办法,一味的用简单排序。
四、改进建议
还是课上要认真听课做笔记,闲暇时间要多花时间看看题目代码,多分析下类与类的结构功能啥的,也建议老师在每次作业结束后及时给出正确答案以供参考,或者在课上进行讲解
,以便我们学生的问题困惑可以及时解决

五、总结

总的来说这几次题目集还是相当有难度的,而且量也是相当的多,通过这几次的作业以及期中考试,我学会了接口,多态,类与类结构等等的
概念和应用,对java的理解和使用又熟悉了许多,相信之后的学习也可以更加熟练。
 

标签:lineArray,题目,期中考试,System,PTA,int,return,order,out
From: https://www.cnblogs.com/nchu21207118/p/17842807.html

相关文章

  • pta博客二
    前言在这次pta题目集4~6中,我们有了前三次基础java作业的基础,正式开始对java实验的进阶,其中的菜单计价程序的难度逐渐增大,第五次和第六次pta作业都是在第四次作业菜单计价程序-三上进行添加的,难度有点大。在这三次题目集当中,因为对于java函数的使用不算熟练,有些函数实现的代码还......
  • PTA4-6、期中考试总结Blog-2
    本次Blog是针对Java程序设计的PTA题目集4-6以及期中考试的总结。一、前言:题目集4共四道题,包括菜单计价系列题目两道、单词统计与排序、 判断两个日期的先后,计算间隔天数、周数。题目难度适中,其中菜单计价2-3难度较大。考察的主要是正则表达式运算、哈希表的运用等。题目集5只有......
  • 南昌航空大学JAVA Blog-2题目4-6期中考试
    一.前言 在进行题目集4-6的练习时,老师课堂上讲的内容一般都会围绕在这次题目集需要用到的新内容上。对于题目集代码的完成有很大的帮助,如课堂讲的封装、继承、多态等内容,简化了代码修改的难度,正则表达式则在一定程度上减少了代码量。但是就我个人认为,这几次的题目集除了期中考试......
  • 题目集4-6以及期中的总结
    前言:目前完成了一些关于Java的编程练习题,并且在逐渐掌握Java语言的基本知识和编程技巧。每个题目都涉及不同的知识点和概念,通过挑战自己解决问题,本人有效地学习和应用这些知识。对于复杂的题目集,确实需要更多的时间和精力来理解和解决。尽管如此,坚持练习,并解决各种难题会帮助提高......
  • PTA题目集4、5、6以及期中考试的总结性Blog
    一.前言    大三上学期开始,我们开始接触java这门语言,Java具有大部分编程语言所共有的一些特征,被特意设计用于互联网的分布式环境。Java具有类似于C++语言的形式和感觉,但它要比C++语言更易于使用,而且在编程时彻底采用了一种以对象为导向的方式。    pta已经写了六......
  • 第二次blog-对菜单系统和期中考试的总结
     一、前言这三次菜单的更迭,基本每次都是在前一次的基础上增加部分功能,总体改动不是特别大,越到后期菜单系统越完善时功能修改的速度也更快。主要问题在于一开始的框架没有建好,输入信息后对信息的相关处理没有采取一个清晰地任务分割,而是堆砌在了主函数中,大量ifelse语句增......
  • PTA题目集4、5、6以及期中考试的总结性Blog
    第二次博客一、前言​ 对于PTA题目集4.5.6都是对于菜单题目的不断迭代,难度也是越来越高,对于第四次pta第三题也就是菜单二中main函数代码还是很少的,到了菜单三中的一下关键的逻辑代码就放到了主函数中,到后面不断的迭代主函数的内容也是在不断地增加。还是在类设计方面没有做的很......
  • PTA4、5、6及期中考试总结
    本次是第二次博客,主要的习题是pta4、5、6以及期中考试,pta的题目主要是延续了之前的菜单题目,相较于之前的菜单增加了许多功能如增加桌号,增加时间,增加了特色菜,增加删除某条记录等,期中考试的题目则是选择题加上大题目,选择题是对Java的一些基础知识的考察,大题目主要考察了类的设计,继承......
  • 题目(九)
    1,#include<stdio.h>intmain(){intarr[]={1,2,3,4,5};short*p=(short*)arr;inti=0;for(i=0;i<4;i++){*(p+i)=0;}for(i=0;i<5;i++){printf("%d",arr[i]);}return0;}上面代码的结果是()2,下面关......
  • PTA题目集4~6+期中总结
    目录:1.前言2.设计与分析3.BUG与修正4.缺陷与改进5.总结一、前言题目集4的主要难点是在菜单2和菜单3,大概只有一半的同学通过了全部测试点。主要的原因是这次的题目相比之前的题目,类与类之间的关系更加紧密了,也更加复杂了。也正......