1.前言
在当今信息爆炸的时代,Java作为一门强大且广泛应用的编程语言,已经成为了众多开发者的首选。它的跨平台性、健壮性以及丰富的生态系统,使得它在企业级应用、移动应用、大数据处理等领域都有着广泛的应用。
本博客我们将会深入探讨Java语言的基础概念和核心特性,如面向对象编程、多线程、异常处理等,以帮助读者建立坚实的编程基础。希望您在这里能够获取到有价值的知识,并与我们一起共同成长。让我们开始这段Java的旅程吧!
关于这三次pta作业做出总结,总的来说三次作业每一次都比上一次更难,难度依次上升。
2. 设计与分析
7-4 菜单计价程序-2
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String []menu =new String[500];
int []price=new int[500];
String menuName;
int inputPrice;
int i=0;
String wholeJudge;
while(true)
{
int reption=1;
menuName=input.next();
if(menuName.equals("1"))
{
wholeJudge="1";
break;
}
if(menuName.equals("end"))
{
wholeJudge="0";
break;
}
inputPrice=input.nextInt();
for(int k=0;k<i;k++)
if(menuName.equals(menu[k]))
{
price[k]=inputPrice;reption=0;
break;
}
if(reption==1)
{
menu[i]=menuName;
price[i]=inputPrice;
i++;
}
}
int everyPrice=0;
int totalPrice = 0;
int count=0;
int []recording=new int[100];
int re=0;
int judge3=1,judge2=0;
String endJudge="";
if(wholeJudge.equals("1"))
while(!wholeJudge.equals("end"))
{
everyPrice=0;
int flag=0;
String order=input.next();
if(order.equals("delete"))
{
if(judge2==1&&judge3==0)
wholeJudge = endJudge;
int p=Integer.parseInt(wholeJudge);
if(p<1||p>count||recording[p-1]==0)
System.out.println("delete error;");
if(p>=1&&p<=count&&recording[p-1]!=0)
{
totalPrice -= recording[p-1];
recording[p-1]=0;
}
endJudge = input.next();
judge3 = 0;
if(endJudge.equals("end"))
break;
else
{
judge2=1;
wholeJudge=endJudge;
continue;
}
}
else judge3=1;
int size1=input.nextInt();
int b=input.nextInt();
for(int j=0;j<i;j++)
{
if(order.equals(menu[j]))
{
flag=1;
if(size1==1)everyPrice+=price[j];
if(size1==2)
{
if(price[j]%2==1)
everyPrice+=price[j]*1.5+1;
else
everyPrice+=price[j]*1.5;
}
if(size1==3)
everyPrice+=2*price[j];
}
}
if(flag==0)
{
recording[re++]=0;
System.out.println(order+" does not exist");
count++;
}
if(flag==1)
{
everyPrice*=b;
totalPrice+=everyPrice;
recording[re++]=everyPrice;
System.out.println(wholeJudge+" "+order+" "+everyPrice);
count++;
}
wholeJudge=input.next();
}
if(!wholeJudge.equals("0"))
System.out.println(totalPrice);
else System.out.println("0");
}
}
/*
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.util.Scanner;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
String dateString1 = scanner.next();
String dateString2 = scanner.next();
LocalDate date1 = LocalDate.parse(dateString1, formatter);
LocalDate date2 = LocalDate.parse(dateString2, formatter);
long weeks = ChronoUnit.WEEKS.between(date1, date2);
long days = ChronoUnit.DAYS.between(date1, date2);
if (date1.isBefore(date2)) {
System.out.println("第一个日期比第二个日期更早");
} else if (date1.isAfter(date2)) {
System.out.println("第一个日期比第二个日期更晚");
} else {
System.out.println("同一天");
}
System.out.println("两个日期间隔" + Math.abs(days) + "天");
System.out.print("两个日期间隔" + Math.abs(weeks) + "周");
}
*/
分析:该程序相比与菜单-1增加了用户删减菜的功能,模板还是套用菜单计价程序-1,但因有了这功能输入的情况也变得随之不一样了,菜品的数量也不一样。一开始我认为,可能并不太难,因为我们有了第一次的经验,相较于之前的代码,,调试时发现我的操作与数据无法相对应,它们之间毫无关联,发现没有这么简单,最后解决了该问题。
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.util.Scanner;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d");
String dateString1 = scanner.next();
String dateString2 = scanner.next();
LocalDate date1 = LocalDate.parse(dateString1, formatter);
LocalDate date2 = LocalDate.parse(dateString2, formatter);
long weeks = ChronoUnit.WEEKS.between(date1, date2);
long days = ChronoUnit.DAYS.between(date1, date2);
if (date1.isBefore(date2)) {
System.out.println("第一个日期比第二个日期更早");
} else if (date1.isAfter(date2)) {
System.out.println("第一个日期比第二个日期更晚");
} else {
System.out.println("同一天");
}
System.out.println("两个日期间隔" + Math.abs(days) + "天");
System.out.print("两个日期间隔" + Math.abs(weeks) + "周");
}
}
7-1 菜单计价程序-4
import java.time.LocalTime;
import java.util.*;
public class Main {
public static void main(String[] args) {
Menu menu = new Menu();
Scanner input = new Scanner(System.in);
Order[] orders = new Order[10000];
Table[] tables = new Table[10000];
int i = 0;
String nextLine = input.nextLine();
while (!nextLine.equals("end")) {
String[] lineArray = nextLine.split(" ");
if ("table".equals(lineArray[0])) {
orders[i] = new Order(menu);
int[] delete = new int[10];
int del = 0;
int orderDish = 0;
if (lineArray.length != 4) {
System.out.println("wrong format");
nextLine = input.nextLine();
while (!nextLine.equals("end")) {
String[] lineArray1 = nextLine.split(" ");
if ("table".equals(lineArray1[0])) {
break;
}else {
nextLine = input.nextLine();
}
}
continue;
}
if (!lineArray[0].equals("table")) {
System.out.println("wrong format");
nextLine = input.nextLine();
while (!nextLine.equals("end")) {
String[] lineArray1 = nextLine.split(" ");
if ("table".equals(lineArray1[0])) {
break;
}else {
nextLine = input.nextLine();
}
}
continue;
}
if (!(lineArray[1].matches("[1-9]|[1-4][0-9]|5[0-5]"))) {
System.out.println("wrong format");
nextLine = input.nextLine();
while (!nextLine.equals("end")) {
String[] lineArray1 = nextLine.split(" ");
if ("table".equals(lineArray1[0])) {
break;
}else {
nextLine = input.nextLine();
}
}
continue;
}
int tableNum= Integer.parseInt(lineArray[1]);
String[] date = lineArray[2].split("/");
String[] time = lineArray[3].split("/");
if (!(date[0].matches("[0-9]{4}") &&
date[1].matches("[0-9]{1,2}") &&
date[2].matches("[0-9]{1,2}") &&
time[0].matches("[0-9]{1,2}") &&
time[1].matches("[0-9]{1,2}") &&
time[2].matches("[0-9]{1,2}"))) {
System.out.println("wrong format");
nextLine = input.nextLine();
while (!nextLine.equals("end")) {
String[] lineArray1 = nextLine.split(" ");
if ("table".equals(lineArray1[0])) {
break;
}else {
nextLine = input.nextLine();
}
}
continue;
}
if (!(date[1].matches("[1-9]|1[0-2]|0[1-9]") &&
time[0].matches("[0-9]|0[0-9]|1[0-9]|2[0-4]") &&
time[1].matches("[0-9]|0[0-9]|[1-5][0-9]") &&
time[2].matches("[0-9]|0[0-9]|[1-5][0-9]"))) {
System.out.println(tableNum + " date error");
nextLine = input.nextLine();
while (!nextLine.equals("end")) {
String[] lineArray1 = nextLine.split(" ");
if ("table".equals(lineArray1[0])) {
break;
}else {
nextLine = input.nextLine();
}
}
continue;
}
Calendar calendar= Calendar.getInstance();
calendar.set(Integer.parseInt(date[0]),
Integer.parseInt(date[1]),
Integer.parseInt(date[2]));;
LocalTime localTime = LocalTime.of(Integer.parseInt(time[0]),
Integer.parseInt(time[1]),
Integer.parseInt(time[2]));
if (!isDate(calendar)) {
System.out.println("not a valid time period");
nextLine = input.nextLine();
while (!nextLine.equals("end")) {
String[] lineArray1 = nextLine.split(" ");
if ("table".equals(lineArray1[0])) {
break;
}else {
nextLine = input.nextLine();
}
}
continue;
}
System.out.println("table " + tableNum + ": ");
nextLine = input.nextLine();
while (!nextLine.equals("end")) {
String[] lineArray1 = nextLine.split(" ");
if ("table".equals(lineArray1[0])) {
break;
} else if ("table".equals(lineArray1[0] + lineArray1[1])) {
System.out.println("wrong format");
} else if (lineArray1.length == 5) {
Dish dish = new Dish();
dish = menu.searthDish(lineArray1[2]);
orderDish = dish.getPrice(Integer.parseInt(lineArray1[3])) *
Integer.parseInt(lineArray1[4]);
System.out.println(lineArray1[1] + " table " + tableNum +
" pay for table " + lineArray1[0] + " " + orderDish);
} else if (lineArray1.length == 4) {
int orderNum;
String dishName = lineArray1[1];
int portion;
int num;
if (lineArray1[0].matches("[1-9]|[1-9][0-9]")) {
orderNum = Integer.parseInt(lineArray1[0]);
}else {
orderNum = 0;
}
if (lineArray1[2].matches("[1-9]")) {
portion = Integer.parseInt(lineArray1[2]);
}else {
portion = 0;
}
if (lineArray1[3].matches("[1-9]|[1-9][0-9]")) {
num = Integer.parseInt(lineArray1[3]);
}else {
num = 0;
}
orders[i].addARecord(orderNum,dishName,portion,num);
} else if ("delete".equals(lineArray1[1])) {
int flag = 0;
delete[del] = Integer.parseInt(lineArray1[0]);
for (int j = del;j >= 1;j --) {
if (delete[j] == delete[j-1]) {
System.out.println("deduplication " + delete[del]);
flag = 1;
}
}
if (flag == 0) {
orders[i].delARecordByOrderNum(Integer.parseInt(lineArray1[0]));
}
del ++;
} else if (lineArray1.length == 2) {
System.out.println("invalid dish");
}else {
System.out.println("wrong format");
}
nextLine = input.nextLine();
}
tables[i] = new Table(orders[i],tableNum,calendar,localTime);
tables[i].setOrderDish(orderDish);
i ++;
} else if (lineArray.length == 2) {
if (lineArray[1].matches("[1-9]|[1-2][0-9]{1,2}")) {
menu.addDish(lineArray[0], Integer.parseInt(lineArray[1]));
} else if (lineArray[1].matches("0|[3-9][0-9]{1,2}")) {
System.out.println(lineArray[0] + " price out of range " +
Integer.parseInt(lineArray[1]));
}else {
System.out.println("wrong format");
}
nextLine = input.nextLine();
} else if (lineArray.length == 3) {
if (lineArray[1].matches("[1-9]|[1-2][0-9]{2}")) {
menu.addDish(lineArray[0],Integer.parseInt(lineArray[1]),lineArray[2]);
} else if (lineArray[1].matches("0|[3-9][0-9]{2}")) {
System.out.println(lineArray[0] + " price out of range " +
Integer.parseInt(lineArray[1]));
}else {
System.out.println("wrong format");
}
nextLine = input.nextLine();
}else {
System.out.println("wrong format");
nextLine =input.nextLine();
}
}
for (int j = 0;j < i;j ++) {
tables[j].getTotalPrice();
}
}
public static boolean isDate(Calendar calendar) {
int[] maxNum = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if ((calendar.get(Calendar.YEAR) == 2022 ||
calendar.get(Calendar.YEAR) == 2023) &&
(calendar.get(Calendar.MONTH) >=1 &&
calendar.get(Calendar.MONTH) <= 12) &&
(calendar.get(Calendar.DATE) >= 1 &&
calendar.get(Calendar.DATE) <= maxNum[calendar.get(Calendar.MONTH)])) {
return true;
}else {
return false;
}
}
}
class Table {
int num;
Calendar calendar = Calendar.getInstance();
LocalTime localTime = LocalTime.now(); ;
Order order;
private int orderDish = 0;
public int getOrderDish() {
return orderDish;
}
public void setOrderDish(int orderDish) {
this.orderDish = orderDish;
}
public Table() {
}
public Table (int num) {
this.num = num;
}
public Table(Order order,int num,Calendar calendar,LocalTime localTime) {
this.order = order;
this.num = num;
this.calendar = calendar;
this.localTime = localTime;
}
public boolean isOpeningHours() {
if (this.calendar.get(Calendar.DAY_OF_WEEK) == 3 ||
this.calendar.get(Calendar.DAY_OF_WEEK) == 4) {
if (localTime.getHour() >9 &&
localTime.getHour() <= 21) {
return true;
} else if ((localTime.getHour() == 9 &&
localTime.getMinute() >= 30) ||
(localTime.getHour() == 21 &&
localTime.getMinute() < 30)) {
return true;
} else if (localTime.getHour() == 21 &&
localTime.getMinute() == 30 &&
localTime.getSecond() == 0) {
return true;
}else {
return false;
}
}else {
if ((localTime.getHour() > 10 &&
localTime.getHour() <= 14) ||
(localTime.getHour() >= 17 &&
localTime.getHour() <= 20)) {
return true;
} else if ((localTime.getHour() == 10 &&
localTime.getMinute() >= 30) ||
(localTime.getHour() == 14 &&
localTime.getMinute() < 30) ||
(localTime.getHour() == 20 &&
localTime.getSecond() < 30)) {
return true;
} else if ((localTime.getHour() == 10 &&
localTime.getMinute() == 30 &&
localTime.getSecond() == 0) ||
(localTime.getHour() == 20 &&
localTime.getMinute() == 30 &&
localTime.getSecond() == 0)) {
return true;
}else {
return false;
}
}
}
public double discount() {
if (this.calendar.get(Calendar.DAY_OF_WEEK) == 3 ||
this.calendar.get(Calendar.DAY_OF_WEEK) == 4) {
return 1;
}else {
if (localTime.getHour() >= 17 &&
localTime.getHour() <= 20) {
return 0.8;
} else if (localTime.getHour() == 20 &&
localTime.getSecond() < 30) {
return 0.8;
} else if (localTime.getHour() == 20 &&
localTime.getMinute() == 30 &&
localTime.getSecond() == 0) {
return 0.8;
} else if ((localTime.getHour() > 10 &&
localTime.getHour() <= 14)) {
return 0.6;
} else if ((localTime.getHour() == 10 &&
localTime.getMinute() >= 30) ||
(localTime.getHour() == 14 &&
localTime.getMinute() < 30)) {
return 0.6;
} else if ((localTime.getHour() == 10 &&
localTime.getMinute() == 30 &&
localTime.getSecond() == 0)) {
return 0.6;
}
}
return 0;
}
public double discountNew() {
if (this.calendar.get(Calendar.DAY_OF_WEEK) == 3 ||
this.calendar.get(Calendar.DAY_OF_WEEK) == 4) {
return 1;
}else {
return 0.7;
}
}
public void getTotalPrice() {
double sum = 0;
if (isOpeningHours()) {
for (Record record:this.order.getRecords()
) {
int price = record.getPrice();
if (record.getD().specialDish.equals("T")) {
if (!record.isDelete()) {
sum += Math.round(price) * discountNew();
}
}else {
if (!record.isDelete()) {
sum += Math.round(price) * discount();
}
}
}
System.out.println("table " + this.num + ": " +
order.getTotalPrice() + " " +
Math.round(sum));
}else {
System.out.println("table " + this.num + " out of opening hours");
}
}
}
class Menu {
private List<Dish> dishes = new ArrayList<>();//菜品数组,保存所有菜品信息
public List<Dish> getDishes() {
return dishes;
}
Dish searthDish(String dishName) {
for (Dish dish : dishes) {
if (dish.getDishName().equals(dishName)) {
return dish;
}
}
return null;
}
//添加一道菜品信息
Dish addDish(String dishName, int unit_price) {
for (Dish dish : dishes) {
if (dish.getDishName().equals(dishName)) {
dish.setUnit_price(unit_price);
return dish;
}
}
Dish dish = new Dish(dishName, unit_price);
dishes.add(dish);
return dish;
}
Dish addDish(String dishName,int unit_price,String orderDish) {
for (Dish dish : dishes) {
if (dish.getDishName().equals(dishName)) {
dish.setUnit_price(unit_price);
return dish;
}
}
Dish dish = new Dish(dishName,unit_price,orderDish);
dishes.add(dish);
return dish;
}
}
class Dish {
String dishName;//菜品名称
int unit_price; //单价
String specialDish;
public String getDishName() {
return dishName;
}
public int getUnit_price() {
return unit_price;
}
public void setDishName(String dishName) {
this.dishName = dishName;
}
public void setUnit_price(int unit_price) {
this.unit_price = unit_price;
}
public Dish(String name, int unit_price) {
this.dishName = name;
this.unit_price = unit_price;
this.specialDish = "F";
}
public Dish(String dishName, int unit_price, String specialDish) {
this.dishName = dishName;
this.unit_price = unit_price;
this.specialDish = specialDish;
}
public Dish() {
}
//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份)
int getPrice(int portion) {
float botSum[] = {1, 1.5f, 2};
return Math.round((unit_price * botSum[portion - 1]));
}
}
class Record {
private int numOrder;//序号
private Dish d;//菜品
private int portion;//份额(1/2/3代表小/中/大份)
private int num;
private boolean isDelete = false;
public boolean isNotFound() {
return notFound;
}
public void setNotFound(boolean notFound) {
this.notFound = notFound;
}
private boolean notFound = false;
public Record(int orderNum, Dish d, int portion, int num) {
this.numOrder = orderNum;
this.d = d;
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 Dish getD() {
return d;
}
public void setD(Dish d) {
this.d = d;
}
public void setPortion(int portion) {
this.portion = portion;
}
public int getPortion() {
return portion;
}
public void setDelete(boolean delete) {
isDelete = delete;
}
public boolean isDelete() {
return isDelete;
}
public void setNum(int num) {
this.num = num;
}
public int getNum() {
return num;
}
}
class Order {
private Menu menu;
private List<Record> records = new ArrayList<>();//保存订单上每一道的记录
public Order(Menu menu) {
this.menu = menu;
}
public List<Record> getRecords() {
return records;
}
public Menu getMenu() {
return menu;
}
//计算订单的总价
int getTotalPrice() {
int sum = 0;
for (Record record : records) {
int price = record.getPrice();
if (!record.isDelete()) {
sum = sum + price;
}
}
return sum;
}
//添加一条菜品信息到订单中
Record addARecord(int orderNum, String dishName, int portion, int num) {
if (orderNum == 0) {
System.out.println("wrong format");
return null;
}
Dish dish = menu.searthDish(dishName);
if (dish == null) {
System.out.println(dishName + " does not exist");
return null;
}
if (portion == 0) {
System.out.println("wrong format");
return null;
}
if (dish.specialDish.equals("T")) {
if (portion != 1 && portion != 2 && portion != 3) {
System.out.println(orderNum + " portion out of range " + portion);
return null;
}
} else if (dish.specialDish.equals("F")) {
if (portion != 1 && portion !=2 && 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;
} else if (num == 0) {
System.out.println("wrong format");
return null;
}
Record record = new Record(orderNum, dish, portion, num);
for (int i = 0;i < records.size();i ++) {
if (records.get(i).getNumOrder() >= record.getNumOrder()) {
System.out.println("record serial number sequence error");
return null;
}
}
records.add(record);
int price = record.getPrice();
System.out.println(record.getNumOrder() + " " + record.getD().getDishName() + " " + price);
return record;
}
public boolean delARecordByOrderNum(int orderNum) {
for (Record record : records) {
if (!record.isNotFound() && !record.isDelete() && record.getNumOrder() == orderNum) {
record.setDelete(true);
return true;
}
}
System.out.println("delete error");
return false;
}
}
本次课题比菜单计价系列-3增加的异常情况:
1、菜谱信息与订单信息混合,应忽略夹在订单信息中的菜谱信息。输出:"invalid dish"
2、桌号所带时间格式合法(格式见输入格式部分说明,其中年必须是4位数字,月、日、时、分、秒可以是1位或2位数),数据非法,比如:2023/15/16 ,输出桌号+" date error"
3、同一桌菜名、份额相同的点菜记录要合并成一条进行计算,否则可能会出现四舍五入的误差。
4、重复删除,重复的删除记录输出"deduplication :"+序号。
5、代点菜时,桌号不存在,输出"Table number :"+被点菜桌号+" does not exist";本次作业不考虑两桌记录时间不匹配的情况。
6、菜谱信息中出现重复的菜品名,以最后一条记录为准。
7、如果有重复的桌号信息,如果两条信息的时间不在同一时间段,(时段的认定:周一到周五的中午或晚上是同一时段,或者周末时间间隔1小时(不含一小时整,精确到秒)以内算统一时段),此时输出结果按不同的记录分别计价。
8、重复的桌号信息如果两条信息的时间在同一时间段,此时输出结果时合并点菜记录统一计价。前提:两个的桌号信息的时间都在有效时间段以内。计算每一桌总价要先合并符合本条件的饭桌的点菜记录,统一计价输出。
9、份额超出范围(1、2、3)输出:序号+" portion out of range "+份额,份额不能超过1位,否则为非法格式,参照第13条输出。
10、份数超出范围,每桌不超过15份,超出范围输出:序号+" num out of range "+份数。份数必须为数值,最高位不能为0,否则按非法格式参照第16条输出。
11、桌号超出范围[1,55]。输出:桌号 +" table num out of range",桌号必须为1位或多位数值,最高位不能为0,否则按非法格式参照第16条输出。
12、菜谱信息中菜价超出范围(区间(0,300)),输出:菜品名+" price out of range "+价格,菜价必须为数值,最高位不能为0,否则按非法格式参照第16条输出。
13、时间输入有效但超出范围[2022.1.1-2023.12.31],输出:"not a valid time period"
14、一条点菜记录中若格式正确,但数据出现问题,如:菜名不存在、份额超出范围、份数超出范围,按记录中从左到右的次序优先级由高到低,输出时只提示优先级最高的那个错误。
15、每桌的点菜记录的序号必须按从小到大的顺序排列(可以不连续,也可以不从1开始),未按序排列序号的输出:"record serial number sequence error"。当前记录忽略。(代点菜信息的序号除外)
16、所有记录其它非法格式输入,统一输出"wrong format"
17、如果记录以“table”开头,对应记录的格式或者数据不符合桌号的要求,那一桌下面定义的所有信息无论正确或错误均忽略,不做处理。如果记录不是以“table”开头,比如“tab le 55 2023/3/2 12/00/00”,该条记录认为是错误记录,后面所有的信息并入上一桌一起计算。
7-1 菜单计价程序-5
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
public static void main(String[] args) throws ParseException {
Menu menu = new Menu();
// 读入菜单信息
Scanner sc = new Scanner(System.in);
String menuLine = sc.nextLine();
while (!menuLine.startsWith("table")) {
String[] menuInfo = menuLine.split(" ");
if (menuInfo.length == 2) {
String name = menuInfo[0];
int unit_price = Integer.parseInt(menuInfo[1]);
if (menu.searchDish(name) == null) {
menu.addDish(name, unit_price);
}
} else if (menuInfo.length == 4 && menuLine.endsWith("T")) {
String name = menuInfo[0];
String type = menuInfo[1];
int unit_price = Integer.parseInt(menuInfo[2]);
Map<String, String> map = new HashMap<String, String>() {
{
put("川菜", "Chuan");
put("晋菜", "Jin");
put("浙菜", "Zhe");
}
};
DishType dishType = DishType.valueOf(map.get(type));
if (menu.searchDish(name) == null) {
menu.addDish(name, unit_price, dishType);
}
} else {
System.out.println("wrong format");
}
menuLine = sc.nextLine();
}
ArrayList<Table> tables = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
// 读入订单信息
int tableId = 0;
String name = null;
String phone = null;
Date date = null;
Date time = null;
boolean legaltime = true;
boolean legalformat = true;
String orderLine = menuLine;
while (!orderLine.equals("end")) {
String[] orderInfo = orderLine.split(" ");
// 解析桌号标识
if (orderLine.startsWith("table")) {
legalformat = true;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH/mm/ss");
tableId = Integer.parseInt(orderInfo[1]);
name = orderInfo[3];
phone = orderInfo[4];
try {
date = dateFormat.parse(orderInfo[5]);
time = timeFormat.parse(orderInfo[6]);
} catch (Exception e) {
legalformat = false;
System.out.println("wrong format");
orderLine = sc.nextLine();
continue;
}
String regex = "^1(80|81|89|33|35|36)\\d{8}$";
Table table = new Table(tableId, name, phone, date, time);
tables.add(table);
if (name.length() > 10 || !phone.matches(regex)) {
legalformat = false;
System.out.println("wrong format");
orderLine = sc.nextLine();
continue;
}
if (!names.contains(name)) {
names.add(name);
}
if (table.getCoefficient(true) == 0) {
legaltime = false;
System.out.println("table " + table.tableId + " out of opening hours");
} else {
System.out.println(table.printId());
}
} else {
if (legalformat) {
int orderNum;
try {
orderNum = Integer.parseInt(orderInfo[0]);
} catch (Exception e) {
System.out.println("wrong format");
orderLine = sc.nextLine();
continue;
}
if (orderLine.endsWith("delete")) {
if (!tables.get(tableId - 1).delRecordByOrderNum(orderNum)) {
System.out.println("delete error");
}
} else {
if (orderInfo.length == 4) {
String dishName = orderInfo[1];
int portion = Integer.parseInt(orderInfo[2]);
int quantity = Integer.parseInt(orderInfo[3]);
Dish dish = menu.searchDish(dishName);
if (dish == null) {
System.out.println(dishName + " does not exist");
orderLine = sc.nextLine();
continue;
}
Record record = new Record(tableId, orderNum, dish, portion, quantity);
tables.get(tableId - 1).addRecord(record);
if (legaltime) {
System.out.println(record.print(tableId));
}
} else if (orderInfo.length == 5) {
String dishName = orderInfo[1];
int level = Integer.parseInt(orderInfo[2]);
int portion = Integer.parseInt(orderInfo[3]);
int quantity = Integer.parseInt(orderInfo[4]);
Dish dish = menu.searchDish(dishName);
if (dish == null) {
System.out.println(dishName + " does not exist");
orderLine = sc.nextLine();
continue;
}
Record record = new Record(tableId, orderNum, dish, level, portion, quantity);
tables.get(tableId - 1).addRecord(record);
if (legaltime) {
System.out.println(record.print(tableId));
}
} else if (orderInfo.length == 6) {
int givenId = Integer.parseInt(orderInfo[1]);
String dishName = orderInfo[2];
int level = Integer.parseInt(orderInfo[3]);
int portion = Integer.parseInt(orderInfo[4]);
int quantity = Integer.parseInt(orderInfo[5]);
Dish dish = menu.searchDish(dishName);
if (dish == null) {
System.out.println(dishName + " does not exist");
orderLine = sc.nextLine();
continue;
}
Record record1 = new Record(givenId, orderNum, dish, level, portion, quantity);
Record record2 = new Record(givenId, orderNum, dish, level, 0, quantity);
tables.get(tableId - 1).addRecord(record1);
tables.get(givenId - 1).addRecord(record2);
if (legaltime) {
System.out.println(record1.print(tableId));
}
} else {
System.out.println("wrong format");
}
}
}
}
// 读入下一个桌号标识
orderLine = sc.nextLine();
}
sc.close();
for (Table table : tables) {
if (table.flag && table.getTotalPrice() != 0) {
System.out.println(table.printInfo());
}
}
names.sort(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});
for (String costumName : names) {
int sum = 0;
String costumPhone = null;
for (Table table : tables) {
if (table.name.equals(costumName)) {
sum += table.getCheckedPrice();
costumPhone = table.phone;
}
}
if (sum != 0) {
System.out.println(costumName + " " + costumPhone + " " + sum);
}
}
}
}
enum DishType {
Chuan,
Jin,
Zhe,
}
class Dish {
public String name;
public int unit_price;
public DishType type;
public Dish(String name, int unit_price, DishType type) {
this.name = name;
this.unit_price = unit_price;
this.type = type;
}
public Dish(String name, int unit_price) {
this.name = name;
this.unit_price = unit_price;
}
@Override
public String toString() {
return name;
}
}
class Menu {
public ArrayList<Dish> dishs = new ArrayList<>();
public Dish searchDish(String dishName) {
for (Dish dish : dishs) {
if (dish.name.equals(dishName)) {
return dish;
}
}
return null;
}
void addDish(String dishName, int unit_price) {
dishs.add(new Dish(dishName, unit_price));
}
void addDish(String dishName, int unit_price, DishType type) {
dishs.add(new Dish(dishName, unit_price, type));
}
}
class Record {
int orderNum;
Dish dish;
int portion;
int quantity;
int level;
boolean flag;
int givenId;
boolean check_level() {
switch (dish.type) {
case Chuan:
if (level > 5 || level < 0) {
return false;
} else {
return true;
}
case Jin:
if (level > 4 || level < 0) {
return false;
} else {
return true;
}
case Zhe:
if (level > 3 || level < 0) {
return false;
} else {
return true;
}
default:
return true;
}
}
public Record(int givenID, int orderNum, Dish dish, int portion, int quantity) {
this.orderNum = orderNum;
this.dish = dish;
this.portion = portion;
this.quantity = quantity;
this.level = -1;
this.flag = true;
this.givenId = givenID;
}
public Record(int givenId, int orderNum, Dish dish, int level, int portion, int quantity) {
this.orderNum = orderNum;
this.dish = dish;
this.portion = portion;
this.quantity = quantity;
this.level = level;
this.flag = check_level();
this.givenId = givenId;
}
int getPrice() {
if (!flag)
return 0;
double coefficient = 0;
switch (portion) {
case 1:
coefficient = 1;
break;
case 2:
coefficient = 1.5;
break;
case 3:
coefficient = 2;
break;
}
int price = (int) Math.round(dish.unit_price * coefficient) * quantity;
return price;
}
int getCheckedPrice(Double coefficient) {
return (int) Math.round(getPrice() * coefficient);
}
public String print(int tableId) {
if (flag == false) {
switch (dish.type) {
case Chuan:
return "spicy num out of range :" + level;
case Jin:
return "acidity num out of range :" + level;
case Zhe:
return "sweetness num out of range :" + level;
default:
return null;
}
} else {
if (givenId == tableId) {
return orderNum + " " + dish.toString() + " " + getPrice();
}
return orderNum + " table " + tableId + " pay for table " + givenId + " " + getPrice();
}
}
@Override
public String toString() {
return "Record [orderNum=" + orderNum + ", dish=" + dish + ", portion=" + portion + ", quantity=" + quantity
+ ", level=" + level + ", flag=" + flag + ", givenId=" + givenId + "]";
}
}
class Table {
ArrayList<Record> records = new ArrayList<>();
int tableId;
String name;
String phone;
Date date;
Date time;
boolean flag;
public Table(int tableId, String name, String phone, Date date, Date time) {
this.name = name;
this.phone = phone;
this.date = date;
this.time = time;
this.tableId = tableId;
this.flag = true;
}
double getCoefficient(boolean Special) throws ParseException {
double coefficient = 0;
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
// 营业时间
if (dayOfWeek == 1 || dayOfWeek == 7) {
if (time.after(sdfTime.parse("9:29")) && time.before(sdfTime.parse("21:31"))) {
coefficient = 1;
}
} else {
if (time.after(sdfTime.parse("16:59")) && time.before(sdfTime.parse("20:31"))) {
if (Special) {
coefficient = 0.7;
} else {
coefficient = 0.8;
}
} else if (time.after(sdfTime.parse("10:29")) && time.before(sdfTime.parse("14:31"))) {
if (Special) {
coefficient = 0.7;
} else {
coefficient = 0.6;
}
}
}
if (coefficient == 0) {
flag = false;
}
return coefficient;
}
int getTotalPrice() {
int sum = 0;
for (Record record : records) {
sum += record.getPrice();
}
return sum;
}
int getCheckedPrice() throws ParseException {
int sum = 0;
for (Record record : records) {
if (record.level != -1) {
sum += record.getCheckedPrice(getCoefficient(true));
} else {
sum += record.getCheckedPrice(getCoefficient(false));
}
}
return sum;
}
String getAveLevel(DishType type) {
String[] spicy = { "不辣", "微辣", "稍辣", "辣", "很辣", "爆辣" };
String[] acidity = { "不酸", "微酸", "稍酸", "酸", "很酸" };
String[] sweetness = { "不甜", "微甜", "稍甜", "甜" };
double sum = 0;
double num = 0;
for (Record record : records) {
if (record.dish.type == type) {
if (record.flag && tableId == record.givenId) {
num += record.quantity;
sum += record.level * record.quantity;
}
}
}
if (num == 0) {
return "";
}
int ave = (int) Math.round(sum / num);
switch (type) {
case Chuan:
return " 川菜 " + (int) num + " " + spicy[ave];
case Jin:
return " 晋菜 " + (int) num + " " + acidity[ave];
case Zhe:
return " 浙菜 " + (int) num + " " + sweetness[ave];
default:
return null;
}
}
void addRecord(Record record) {
records.add(record);
}
boolean delRecordByOrderNum(int orderNum) {
return records.removeIf(record -> record.orderNum == orderNum);
}
Record findRecordByOrderNum(int orderNum) {
for (Record record : records) {
if (record.orderNum == orderNum) {
return record;
}
}
return null;
}
public String printId() {
return "table " + tableId + ": ";
}
public String printInfo() throws ParseException {
String chuan = getAveLevel(DishType.Chuan);
String jin = getAveLevel(DishType.Jin);
String zhe = getAveLevel(DishType.Zhe);
if (chuan == "" && jin == "" && zhe == "") {
return "table " + tableId + ": " + getTotalPrice() + " " + getCheckedPrice() + " ";
} else {
return "table " + tableId + ": " + getTotalPrice() + " " + getCheckedPrice() + chuan + jin + zhe;
}
}
}
分析:Java 中的多态、继承、封装、堆和栈都是面向对象编程的重要概念,也是Java语言中常用的特性。
多态:
多态即同一种行为可以适用于不同类型的对象。在Java中通过继承和接口实现多态。多态提高了代码的灵活性和可扩展性,使得代码更加易于维护和升级。
继承:
继承是一种重要的代码复用方式,可以创建新的类从现有的类中继承属性和行为。Java 中所有类都从Object类继承,没有明确继承的类默认继承Object类。继承允许我们创建更具体的子类,提高代码的可重用性。
封装:
封装是种面向对象编程的核心原则,它将代码的实现细节隐藏起来,只对外界提供一些公共的接口,保护了代码的安全性和稳定性。Java中通过构造方法、Getters和Setters来实现封装。
接口:
当一个类中的所有方法都是抽象方法的时候,就可以将其定义为接口;接口也是一种引用数据类型,它比抽象类还要抽象
接口存在的两个重要意义
3.一些心得体会
通过这三次作业学习运用正则表达式,明白类之间的关系,成绩类用继承还是组合关系。组合关系更加灵活。通过不同类的组合,可以实现更多样化的功能和计算方式。
对于精度问题也对我造成一点困扰应根据具体的需求选择适当的浮点数类型double类型有着更高的精确度,float类型则更能节约系统空间。
非零返回的问题,编写菜单计价程序的代码时,测试点经常由于非零返回出错,实际上就是程序的语法在中间就出现了异常,或者是没有结束的方法,导致程序可能返回null,判断的逻辑出错了,无法进行到该方法最后的return,因此出现了非零返回的状态。
4.主要困难和改进建议
- 应该多给代码标上备注。没有注释,让我总是忘记写的代码前面这些东西都是干什么的,浪费了很多时间,debug,不要总想着一口吃成胖子,一步步来。
5.总结
- 对于该三次的题目集,我认为对于我自己来说是一个很大的提升,PTA和这次的博客对我们来说都是很重要的提升自己的机会,也能够让我们回过头来给自己的成果予以反思、总结。虽然说过程有点艰难,但自己写出代码并看到它能成功运行时,心里有一种油然而生的成就感。我认为给我们更多的时间,让题目量可以增多但难度适当降低一些,能够增加我们的积极性,让我们对于Java的学习更加有动力。