本次分析菜单2-4,以及期中考试题目,总体来说题目有一定难度,但仍可完成,主要从菜单1过度到2,3时要确定好方向,否则会产生一些无法解决的问题
7-4 菜单计价程序-2
分数:38
输入样例:
在这里给出一组输入。例如:
麻婆豆腐 12
油淋生菜 9
1 麻婆豆腐 2 2
2 油淋生菜 1 3
end
输出样例:
在这里给出相应的输出。例如:
1 麻婆豆腐 36
2 油淋生菜 27
63
代码:(110行实现,除最后测试点外全部通过)
import java.util.*;
class Dish {
public String name;//菜品名称
int unit_price; //单价
int getPrice(int portion) {
if(portion==1) {return unit_price;}
else if (portion == 2) {return (int) Math.round(unit_price*1.5);}
else if (portion ==3) {return unit_price*2;}
else return 0;
}//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份)
}
class Menu {
Dish[] dishs ;//菜品数组,保存所有菜品信息
Dish searthDish(String dishName) {
Dish dish = new Dish();
dish.name = "NULL";
dish.unit_price = 0;
int site = -1;
for(int i=0;i< dishs.length;i++) {
if(dishName.equals(dishs[i].name))
site = i;
}
if(site!=-1) return dishs[site];
else {System.out.println(dishName + " does not exist"); return null;}
}//根据菜名在菜谱中查找菜品信息,返回Dish对象。
}
class Record {
int orderNum;//序号
Dish d;//菜品
int portion;//份额(1/2/3代表小/中/大份)
int num;//数量
void output(){System.out.println(orderNum+" "+d.name+" "+d.getPrice(portion)*num);}
int getPrice() {int nowprice = d.getPrice(portion)*num; return nowprice; }//计价,计算本条记录的价格
}
class Order {
Record[] records;//保存订单上每一道的记录
int getTotalPrice(Menu menu) { //计算订单的总价
int sum = 0;
for(int i=0;i<records.length;i++) {
if(records[i]!=null)
sum+=records[i].getPrice();
}
return sum;
}
Record addARecord(int orderNum,String dishName,int portion,int num,Menu menu) { //添加一条菜品信息到订单中。
Record records = new Record();
records.d =menu.searthDish(dishName);
if(records.d==null)
return null;
records.orderNum = orderNum;
records.portion = portion;
records.num = num;
if (!records.d.name.equals("NULL"))
records.output();
return records;
}
void delARecordByOrderNum(int orderNum){ //根据序号删除一条记录
Record record = findRecordByNum(orderNum);
if(record!=null) {
findRecordByNum(orderNum).num = 0;
} else {System.out.println("delete error;");}
}
Record findRecordByNum(int orderNum){ //根据序号查找一条记录
for(int i=0;i<records.length;i++){
if(records[i]!=null)
if(records[i].orderNum == orderNum){
return records[i];
}
}return null;
}
}
public class Main {
public static void main(String[] args) {
Menu menu = new Menu();
Order order = new Order();
Scanner sc = new Scanner(System.in);
ArrayList<String> Input = new ArrayList<>();
ArrayList<String> dishInput = new ArrayList<>();
ArrayList<String> DeleteInput = new ArrayList<>();
String input = sc.nextLine(); //进行输入
while(!input.equals("end")) {
if(input.charAt(0)>='0'&&input.charAt(0)<='9') {
if(input.split(" ")[1].equals("delete")) {DeleteInput.add(input);}
else {Input.add(input);}
}
else {dishInput.add(input);}
input = sc.nextLine();
} //输入完成
int dishSize = dishInput.size(); //保存菜单
menu.dishs = new Dish[dishSize];
for(int i=0;i<dishSize;i++) {
menu.dishs[i] = new Dish();
menu.dishs[i].name = dishInput.get(i).split(" ")[0];
menu.dishs[i].unit_price = Integer.parseInt(dishInput.get(i).split(" ")[1]);
}//将点单从输入缓冲区送到点单数组↓
order.records= new Record[Input.size()];
for(int i=0;i<Input.size();i++) { //格式化存入点菜记录
order.records[i] = new Record();//初始化
String[] temp= Input.get(i).split(" ");
order.records[i] = order.addARecord(Integer.parseInt(temp[0]), temp[1], //编号+名称
Integer.parseInt(temp[2]), Integer.parseInt(temp[3]),menu); //份数+份额
}
for(int i=0;i<DeleteInput.size();i++) { //格式化修正点菜记录
String[] temp = DeleteInput.get(i).split(" ");
order.delARecordByOrderNum(Integer.parseInt(temp[0]));
}
System.out.println(order.getTotalPrice(menu));//计算总价,输出
}
}
复杂度:
类图:
缺失两分的问题:因为对点菜记录和删除记录是压入数组后分别处理的,因而对点菜穿插删除无法处理(后续通过重构代码已解决)。
7-1 菜单计价程序-3
分数:36分
输入样例:
在这里给出一组输入。例如:
麻婆豆腐 12
油淋生菜 9
table 1 2023/3/22 12/2/3
1 麻婆豆腐 2 2
2 油淋生菜 1 3
end
输出样例:
在这里给出相应的输出。例如:
table 1:
1 麻婆豆腐 36
2 油淋生菜 27
table 1: 38
代码:
package cba;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Dish {
public String name;//菜品名称
int unit_price; //单价
int getPrice(int portion) {
if(portion==1) {
return unit_price;
} else if (portion == 2) {
return (int) Math.round(unit_price*1.5);
} else if (portion ==3) {
return unit_price*2;
} else
return 0;
}//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份)
}
class Menu {
Dish[] dishs ;//菜品数组,保存所有菜品信息
Dish searthDish(String dishName)
{
Dish dish = new Dish();
dish.name = "NULL";
dish.unit_price = 0;
int site = -1;
for(int i=0;i< dishs.length;i++) {
if(dishName.equals(dishs[i].name))
site = i;
}
if(site!=-1)
return dishs[site];
else {
System.out.println(dishName + " does not exist");
return dish;
}
}//根据菜名在菜谱中查找菜品信息,返回Dish对象。
}
class Record {
int DingCaiTale;
int ShangCaiTable;
int orderNum;//序号
Dish d;//菜品
int portion;//份额(1/2/3代表小/中/大份)
int num;//数量
void output(){
if(DingCaiTale==ShangCaiTable)
{
System.out.println(orderNum+" "+d.name+" "+d.getPrice(portion)*num);
}
else
{
System.out.println(orderNum+" table "+DingCaiTale+" pay for table "+ShangCaiTable+" "+d.getPrice(portion)*num);
}
}
int getPrice()
{
int nowprice = d.getPrice(portion)*num;
return nowprice;
}//计价,计算本条记录的价格
}
class Order {
Record[] records ;//保存订单上每一道的记录
int getTotalPrice(Menu menu) { //计算订单的总价
int sum = 0;
for(int i=0;i<records.length;i++)
{
sum+=records[i].getPrice(); }
return sum;
}
Record addARecord(int dingcaizhuo,int shangcaizhuo,int orderNum,String dishName,int portion,int num,Menu menu) { //添加一条菜品信息到订单中。
Record records = new Record();
records.DingCaiTale = dingcaizhuo;
records.ShangCaiTable = shangcaizhuo;
records.d =menu.searthDish(dishName);
records.orderNum = orderNum;
records.portion = portion;
records.num = num;
if (!records.d.name.equals("NULL"))
records.output();
return records;
}
void delARecordByOrderNum(int orderNum){ //根据序号删除一条记录
if(findRecordByNum(orderNum)!=null) {
Record RE = findRecordByNum(orderNum);//.num = 0
RE.num = 0;
RE.orderNum = 0;
} else {
System.out.println("delete error;");
}
}
Record findRecordByNum(int orderNum){ //根据序号查找一条记录
for(int i=0;i<records.length;i++){
if(records[i].orderNum == orderNum){
return records[i];
}
}return null;
}
}
class Table{
int Table_num=0;
Order order ;
int time;
int dayOfWeek;
public double GetDiscount(){
int LiuZhe_min = 103000;
int LiuZhe_max = 143000;
int BaZhe_min = 170000;
int BaZhe_max = 203000;
int WuZheKou_min = 100000;
int WuZheKou_max = 213000;
if (dayOfWeek>=1&&dayOfWeek<=5)
{
if(this.time>=LiuZhe_min&&this.time<=LiuZhe_max)
return 0.6;
else if (this.time>=BaZhe_min&&this.time<=BaZhe_max)
return 0.8;
else
System.out.println("table "+Table_num+" out of opening hours");
}
else if (dayOfWeek>=6)
{
if(this.time>=WuZheKou_min&&this.time<=WuZheKou_max)
return 1;
else
System.out.println("table "+Table_num+" out of opening hours");
}
return 0;
}
public int getDiscountedPrice(Menu menu)
{
//System.out.println(order.records);
return (int) Math.round(order.getTotalPrice(menu)*GetDiscount());
}
}
public class Main {
public static void main(String[] args) {
Menu menu = new Menu();
//Order order = new Order();
Scanner sc = new Scanner(System.in);
ArrayList<String> Input = new ArrayList<>();
ArrayList<String> DAIDIANCANInput = new ArrayList<>();
ArrayList<String> dishInput = new ArrayList<>();
ArrayList<String> DeleteInput = new ArrayList<>();
Map<Integer, List<String>> orderRecords = new HashMap<>();
List <String> DAY = new ArrayList<>();
List <String> TIME = new ArrayList<>();
String input = sc.nextLine(); //进行输入
int tableNumber = -1,table_Count = 0;
while(!input.equals("end")) {
if(input.startsWith("table"))
{
table_Count++;
String[] tableInfo = input.split("\\s");
tableNumber = Integer.parseInt(tableInfo[1]);
DAY.add(tableInfo[2]);
TIME.add(tableInfo[3]);
orderRecords.put(tableNumber, new ArrayList<>());
}
else if(input.charAt(0)>='0'&&input.charAt(0)<='9') {
List<String> orders = orderRecords.get(tableNumber);
orders.add(input);
}
else
{
dishInput.add(input);
}
input = sc.nextLine();
} //输入完成
int dishSize = dishInput.size(); //保存菜单
menu.dishs = new Dish[dishSize];
for(int i=0;i<dishSize;i++) {
menu.dishs[i] = new Dish();
menu.dishs[i].name = dishInput.get(i).split(" ")[0];
menu.dishs[i].unit_price = Integer.parseInt(dishInput.get(i).split(" ")[1]);
}
Table[] table = new Table[table_Count];
for(int i=0;i<table_Count;i++)
{
table[i] = new Table();
table[i].order = new Order();
}
int Temp_input=0;
for (Map.Entry<Integer, List<String>> entry : orderRecords.entrySet()) {//开始分桌遍历
int tableNum = entry.getKey(),input_size = 0;
//开始处理菜单
System.out.println("table " + tableNum +": ");
List<String> orders = entry.getValue();
Input.clear();
dishInput.clear();
DeleteInput.clear();
DAIDIANCANInput.clear();
for (String order1 : orders) {
if(order1.matches("\\d+\\s+\\D+\\s+\\d+\\s+\\d+") ) {
Input.add(order1);
}
else if (order1.matches("\\d+\\s+\\d+\\s+\\D+\\s+\\d+\\s+\\d+"))
{
DAIDIANCANInput.add(order1);
//System.out.println("table " + tableNum +": "+order1);
//System.out.println(tableNum+" 代点餐");
}
else if (order1.matches("\\d+\\s+delete"))
{
DeleteInput.add(order1);
}
}
input_size = Input.size()+DAIDIANCANInput.size();
//System.out.println(input_size+"*****************************************");
table[Temp_input].order.records= new Record[input_size];
//System.out.println(Temp_input+ "***********************");
int ii=0;
for(ii=0;ii<Input.size();ii++) { //格式化存入点菜记录
table[Temp_input].order.records[ii] = new Record();//初始化
String[] temp= Input.get(ii).split(" ");
table[Temp_input].order.records[ii] = table[Temp_input].order.addARecord(tableNum,tableNum, //点菜桌号+上菜桌号
Integer.parseInt(temp[0]), temp[1], //编号+名称
Integer.parseInt(temp[2]), Integer.parseInt(temp[3]),menu); //份数+份额
}
for(;ii<input_size;ii++)
{
table[Temp_input].order.records[ii] = new Record();//初始化
String[] temp= DAIDIANCANInput.get(ii-Input.size()).split(" ");
table[Temp_input].order.records[ii] = table[Temp_input].order.addARecord(tableNum,Integer.parseInt(temp[0]),//点菜桌号+上菜桌号
Integer.parseInt(temp[1]), temp[2], //编号+名称
Integer.parseInt(temp[3]), Integer.parseInt(temp[4]),menu); //份数+份额
}
for(int i=0;i<DeleteInput.size();i++) { //格式化修正点菜记录
String[] temp = DeleteInput.get(i).split(" ");
table[Temp_input].order.delARecordByOrderNum(Integer.parseInt(temp[0]));
}
//处理时间和日期
String DAYTEMP = DAY.get(Temp_input);
String[] ymd = DAYTEMP.split("/");
String year1 = ymd[0];
String month1 = ymd[1];
String RiZi1 = ymd[2];
if(month1.length()==1){
month1 = "0"+month1;
}
if(RiZi1.length()==1){
RiZi1 = "0"+RiZi1;
}
DAYTEMP = year1+"/"+month1+"/"+RiZi1;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.parse(DAYTEMP, formatter);
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
//日期->星期处理完毕
//开始处理时间(格式化)
Pattern pattern = Pattern.compile("^([01]\\d|2[0-3])/([0-5]\\d)/([0-5]\\d)$"); // 定义正则表达式
String time = TIME.get(Temp_input);
Matcher matcher = pattern.matcher(time);
String[] parts = time.split("/");
String hour = parts[0].length() == 1 ? "0" + parts[0] : parts[0];
String minute = parts[1].length() == 1 ? "0" + parts[1] : parts[1];
String second = parts[2].length() == 1 ? "0" + parts[2] : parts[2];
String correctedTime = hour + minute + second;
///时间处理完毕,开始存入类数组中第Temp_input项
table[Temp_input].Table_num = tableNum; //设置桌号
table[Temp_input].dayOfWeek = dayOfWeek.getValue(); //设置点餐日期(星期)
int IntTime =Integer.parseInt(correctedTime);
table[Temp_input].time = IntTime;
//设置点餐时间
Temp_input++;
}
for (int i=0;i<table.length;i++) {
int out = table[i].getDiscountedPrice(menu);
if(out!=0) {
System.out.println("table " + table[i].Table_num + ": " + out);
}
}
}
}
复杂度:
类图:
分析:
一个简单的菜单点餐系统,包括菜品信息、订单记录、桌号和折扣计算等功能。下面分析一下代码结构:
Dish类:表示菜品,包括菜品名称、单价以及计算菜品价格的方法。
Menu类:表示菜单,包括菜品数组和根据菜名查找菜品信息的方法。
Record类:表示订单记录,包括点餐桌号、上菜桌号、菜品、份数、数量以及输出记录和计价的方法。
Order类:表示订单,包括订单记录数组、计算订单总价、添加记录、删除记录和查找记录的方法。
Table类:表示桌号,包括桌号、订单、时间、星期和计算折扣价的方法。
Main类:包括主要的交互逻辑和输入处理部分,在main方法中进行了整个系统的流程控制。
在Main类的main方法中,通过Scanner获取用户输入,然后根据输入内容进行菜单、订单和桌号的初始化。接着遍历所有的订单记录,对每一张订单进行处理,包括点菜记录的格式化存储、时间和日期的处理,最后计算折扣价并输出结果。
整体结构清晰,功能模块化,代码逻辑相对简单明了。
7-1 菜单计价程序-4
分数:98
输入样例:
在这里给出一组输入。例如:
麻婆豆腐 12
油淋生菜 9 T
table 31 2023/2/1 14/20/00
1 麻婆豆腐 1 16
2 油淋生菜 1 2
2 delete
2 delete
end
输出样例:
在这里给出相应的输出。例如:
table 31:
1 num out of range 16
2 油淋生菜 18
deduplication 2
table 31: 0 0
代码:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Dish {
public String name;//菜品名称
int unit_price; //单价
boolean specialty = false;
int getPrice(int portion) {
if(portion==1) {
return unit_price;
} else if (portion == 2) {
return (int) Math.round(unit_price*1.5);
} else if (portion ==3) {
return unit_price*2;
} else
return 0;
}//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份)
public boolean checkdish(String input)
{
String[] dishInput = input.split(" ");
for (String part : dishInput) {
if (part.isEmpty()) {System.out.println("wrong format"); return false;}
}
boolean isNumeric = dishInput[1].matches("[1-9]\\d*");
if (!isNumeric) {System.out.println("wrong format"); return false;}
if(Integer.parseInt(dishInput[1]) > 299) {
System.out.println(dishInput[0]+" price out of range "+Integer.parseInt(dishInput[1]));
return false;
}
this.name = dishInput[0];
this.unit_price = Integer.parseInt(dishInput[1]);
if (dishInput.length==3)
if(!dishInput[2].equals("T")){System.out.println("wrong format"); return false;}
else
this.specialty = true;
return true;
}
}
class Menu {
ArrayList<Dish> dishes = new ArrayList<>();
Dish searthDish(String dishName){// 倒序遍历,获取最后一个符合菜名的菜品
Dish dish = new Dish();
dish = null;
int site = -1;
for(int i=dishes.size()-1;i>-1;i--) {
if(dishName.equals(dishes.get(i).name)) {
site = i;
break;
}
}
if(site!=-1)
return dishes.get(site);
else {
return dish;
}
}//根据菜名在菜谱中查找菜品信息,返回Dish对象。
}
class Record {
int DingCaiTale;
int ShangCaiTable;
int orderNum;//序号
Dish d;//菜品
int portion;//份额(1/2/3代表小/中/大份)
int num;//数量
int getPrice() {
if(d!=null) {
int nowprice = d.getPrice(portion) * num;
return nowprice;
}
return 0;
}//计价,计算本条记录的价格
boolean check_record(String input,Table table,ArrayList<Integer> zhuohao,Menu menu,int ordercount) {
String[] record_input = input.split(" ");
if (record_input.length == 4)
{
for (String part : record_input) {
if (part.isEmpty()) {System.out.println("wrong format"); return false;}
}
if (!record_input[0].matches("[1-9]\\d*")) {System.out.println("wrong format");return false;}
int orderNum = Integer.parseInt(record_input[0]);
if (ordercount>0)
{
if (orderNum<=table.order.records.get(ordercount-1).orderNum)
{System.out.println("record serial number sequence error");return false;}
}
int portion = Integer.parseInt(record_input[2]);
int num = Integer.parseInt(record_input[3]);
Dish dish;
dish = menu.searthDish(record_input[1]);
if (dish==null)
{System.out.println(record_input[1]+" does not exist"); return false;}
if (portion<1|portion>3)
{System.out.println(orderNum+" portion out of range "+portion); return false;}
if (num<1|num>15)
{System.out.println(orderNum+" num out of range "+num); return false;}
DingCaiTale = table.num;
ShangCaiTable = table.num;
this.orderNum = orderNum;
d = dish;
this.portion = portion;
this.num = num;
if(d!=null) System.out.println(orderNum+" "+record_input[1]+" "+getPrice());
} else if (record_input.length == 5) {
int ShangCaiTable = Integer.parseInt(record_input[0]);
int orderNum = Integer.parseInt(record_input[1]);
int portion = Integer.parseInt(record_input[3]);
int num = Integer.parseInt(record_input[4]);
Dish dish;
dish = menu.searthDish(record_input[2]);
if (dish==null)
{System.out.println(record_input[2]+" does not exist"); return false;}
if (portion<1|portion>3)
{System.out.println(orderNum+" portion out of range "+portion); return false;}
if (num<1|num>15)
{System.out.println(orderNum+" num out of range "+num); return false;}
DingCaiTale = table.num;
this.ShangCaiTable = ShangCaiTable;
boolean zhaozhup = false;
if(DingCaiTale == ShangCaiTable) {System.out.println("Table number :"+ShangCaiTable+" does not exist");return false;}
else
{
for (int a : zhuohao) {
if (ShangCaiTable == a){
zhaozhup = true;
break;
}
//System.out.println(table);
}
if (!zhaozhup) {System.out.println("Table number :"+ShangCaiTable+" does not exist"); return false;}
}
this.orderNum = orderNum;
d = dish;
this.portion = portion;
this.num = num;
System.out.println(orderNum+" table "+DingCaiTale+" pay for table "+ShangCaiTable+" "+d.getPrice(portion)*num);
}
else {
System.out.println("wrong format");
}
return true;
}
}
class Order {
ArrayList<Record> records = new ArrayList<>();
int getTotalPrice() { //计算订单的总价
int sum = 0;
for(int i=0;i<records.size();i++)
{
sum+=records.get(i).getPrice();
}
return sum;
}
void delARecordByOrderNum(int orderNum){ //根据序号删除一条记录
Record record = findRecordByNum(orderNum);
if(record!=null) {
if(record.num==0)
{
System.out.println("deduplication "+record.orderNum);
return;
}
findRecordByNum(orderNum).num = 0;
} else {
System.out.println("delete error;");
}
}
Record findRecordByNum(int orderNum){ //根据序号查找一条记录
for(int i=0;i<records.size();i++){
if(records.get(i).orderNum == orderNum){
return records.get(i);
}
}return null;
}
}
class Table{
int num;
Order order = new Order();
int time;
int dayOfWeek;
public double GetDiscount(){
int LiuZhe_min = 103000;
int LiuZhe_max = 143000;
int BaZhe_min = 170000;
int BaZhe_max = 203000;
int WuZheKou_min = 100000;
int WuZheKou_max = 213000;
if (dayOfWeek>=1&&dayOfWeek<=5)
{
if(this.time>=LiuZhe_min&&this.time<=LiuZhe_max)
return 0.6;
else if (this.time>=BaZhe_min&&this.time<=BaZhe_max)
return 0.8;
else {
System.out.println("table " + num + " out of opening hours");
return -1;
}
}
else if (dayOfWeek>=6)
{
if(this.time>=WuZheKou_min&&this.time<=WuZheKou_max)
return 1;
else {
System.out.println("table " + num + " out of opening hours");
return -1;
}
}
return 0;
}
public int getOriginalPrice() {
//System.out.println(order.records);
return order.getTotalPrice();
}
public int getTotalDiscountedice() {
int sum = 0;
for(int i=0;i<order.records.size();i++)
{
if (order.records.get(i).d!=null) {
double zhekou = GetDiscount(), price_temp = 0;
price_temp = order.records.get(i).getPrice();
if (order.records.get(i).d.specialty && zhekou != 1) {
price_temp *= 0.7;
} else {
price_temp *= zhekou;
}
sum += (int) Math.round(price_temp);
}
}
return sum;
}
public boolean checkTable(String input) {
if (input.endsWith(" ")) {System.out.println("wrong format"); return false;}
String[] table_input = input.split(" ");
if (table_input.length>4) {System.out.println("wrong format"); return false;}
if (!table_input[1].matches("[1-9]\\d*")) {System.out.println("wrong format"); return false;}
num = Integer.parseInt(table_input[1]);
if(num>55||num<1) {System.out.println(num +" table num out of range"); return false;}
if(!checkTableDate(table_input[2])) return false;
if(!checkTableTime(table_input[3])) return false;
return true;
}
private boolean checkTableDate(String input) {
String[] date_input = input.split("/");
int nian =0,yue = 0,ri = 0;
if (date_input.length!=3) {System.out.println("wrong format"); return false;}
if (date_input[0].length() != 4 | date_input[1].length() > 2 | date_input[2].length() > 2) {
System.out.println("wrong format"); return false;
} else {
nian = Integer.parseInt(date_input[0]);
yue = Integer.parseInt(date_input[1]);
ri = Integer.parseInt(date_input[2]);
int[] tianshu = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (yue>12||yue<1)
{System.out.println(num + " date error");return false;}
if (ri>tianshu[yue-1])
{System.out.println(num + " date error");return false;}
if (nian < 2022 || Integer.parseInt(date_input[0]) > 2023) {
System.out.println("not a valid time period");
return false;
}
}
String str0 = String.format("%04d", nian);
String str1 = String.format("%02d", yue);
String str2 = String.format("%02d", ri);
String DAYTEMP= str0 +"/"+str1 +"/"+str2;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.parse(DAYTEMP, formatter);
DayOfWeek DayOfWeek = localDate.getDayOfWeek();
this.dayOfWeek = DayOfWeek.getValue();
return true;
}
private boolean checkTableTime(String input) {
String[] time_input = input.split("/");
if (time_input.length!=3) {System.out.println("wrong format"); return false;}
if (time_input[0].length()>2|time_input[1].length()>2|time_input[2].length()>2) {
System.out.println("wrong format"); return false;
} else {
int xiaoshi = Integer.parseInt(time_input[0]);
int fenzhong = Integer.parseInt(time_input[1]);
int miao = Integer.parseInt(time_input[2]);
if(xiaoshi>24|fenzhong>60|miao>60){
System.out.println(num + " date error");return false;
}
time = miao+fenzhong*100+xiaoshi*10000;
int LiuZhe_min = 103000;
int LiuZhe_max = 143000;
int BaZhe_min = 170000;
int BaZhe_max = 203000;
int WuZheKou_min = 100000;
int WuZheKou_max = 213000;
if (dayOfWeek>=1&&dayOfWeek<=5)
{
if(this.time>=LiuZhe_min&&this.time<=LiuZhe_max);
else if (this.time>=BaZhe_min&&this.time<=BaZhe_max);
else {
System.out.println("table " + num + " out of opening hours");
return false;
}
}
else if (dayOfWeek>=6)
{
if(this.time>=WuZheKou_min&&this.time<=WuZheKou_max);
else {
System.out.println("table " + num + " out of opening hours");
return false;
}
}
}
return true;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Menu menu = new Menu(); //一个menu,
Table table = null;
boolean dish_switch = true,order_switch = false,table_error_switch = false; //两个开关
int ordercount = 0;
List<Table> tables = new ArrayList<>();
ArrayList<Integer> zhuohao = new ArrayList<>();
String input = sc.nextLine();
while(!input.equals("end")) {
if (input.isEmpty()) System.out.println("wrong format");
else if (input.matches("^[\u4e00-\u9fa5].*")&&(!table_error_switch)) {
if (dish_switch) {
Dish dish = new Dish();
if (dish.checkdish(input))
menu.dishes.add(dish);
}
else
System.out.println("invalid dish");
}
else if(input.matches("^[a-zA-Z].*")) {
dish_switch = false;
if (input.startsWith("table"))
{
table = new Table();
if (table.checkTable(input))
{
zhuohao.add(Integer.parseInt(input.split(" ")[1]));
table_error_switch = false;
tables.add(table);
System.out.println("table "+table.num+": ");
order_switch = true;
ordercount = 0;
}
else {order_switch = false;table_error_switch = true;}
}
else {System.out.println("wrong format");}
}
else if (input.matches("^[0-9].*")&&order_switch) {
Record record = new Record();
if(input.matches(".*delete.*")) {
table.order.delARecordByOrderNum(Integer.parseInt(input.split(" ")[0]));
}
else if(record.check_record(input,table,zhuohao,menu,ordercount))
{
table.order.records.add(record);
if (input.split(" ").length==4) {ordercount++;}
}
}
input = sc.nextLine();}//while
for (Table tableout : tables) {
System.out.println("table "+tableout.num+": "+tableout.getOriginalPrice()+" "+tableout.getTotalDiscountedice()); // 以getName()方法为例
}
}
}
复杂度:
由于大量的判断输入合法性,因而圈复杂度较高
类图:
分析:
本次代码进行了重构,重写了Main方法,剥离出检查单独在各个类中执行,减少Main方法的复杂性,通过提前返回等方法减少if的嵌套减少了代码套用,使得代码美观性好。
98分的原因是没有写两桌合并的情况,也就是说同一时间的订单需要合并,但我未处理。
7-1 菜单计价程序-5
分数:90
输入样例1:
桌号时间超出营业范围。例如:
麻婆豆腐 川菜 12 T
油淋生菜 9
麻辣鸡丝 10
table 1 : tom 13605054400 2023/5/1 21/30/00
1 麻婆豆腐 3 1 2
2 油淋生菜 2 1
3 麻婆豆腐 2 3 2
end
输出样例1:
在这里给出相应的输出。例如:
table 1 out of opening hours
代码:
package ecba;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
class Dish {
String name;//菜品名称
int unit_price; //单价
boolean specialty = false;
int classification;
int getPrice(int portion) {
if(portion==1) {
return unit_price;
} else if (portion == 2) {
return (int) Math.round(unit_price*1.5);
} else if (portion ==3) {
return unit_price*2;
} else
return 0;
}//计算菜品价格的方法,输入参数是点菜的份额(输入数据只能是1/2/3,代表小/中/大份)
public boolean checkdish(String input) {
String[] dishInput = input.split(" ");
if (dishInput.length==2) {
this.name = dishInput[0];
this.unit_price = Integer.parseInt(dishInput[1]);
}
else if (dishInput.length == 4) {
this.name = dishInput[0];
this.unit_price = Integer.parseInt(dishInput[2]);
//this.classification = ;
switch (dishInput[1])
{
case "川菜":
classification = 1;
break;
case "晋菜":
classification = 2;
break;
case "浙菜":
classification = 3;
break;
}
this.specialty = true;
}
else {
System.out.println("wrong format"); return false;
}
return true;
}
public boolean checkkouwei(int kouwei) {
if (classification==1) {
if (kouwei>5) {
System.out.println("spicy num out of range :"+kouwei); return false;
}
} else if (classification==2) {
if (kouwei>4) {
System.out.println("acidity num out of range :"+kouwei);return false;
}
} else if (classification==3) {
if (kouwei>3) {
System.out.println("sweetness num out of range :"+kouwei);return false;
}
}
return true;
}
}
class Menu {
ArrayList<Dish> dishes = new ArrayList<>();
Dish searthDish(String dishName){// 倒序遍历,获取最后一个符合菜名的菜品
Dish dish = new Dish();
dish = null;
int site = -1;
for(int i=dishes.size()-1;i>-1;i--) {
if(dishName.equals(dishes.get(i).name)) {
site = i;
break;
}
}
if(site!=-1)
return dishes.get(site);
else {
return dish;
}
}//根据菜名在菜谱中查找菜品信息,返回Dish对象。
}
class Record {
int DingCaiTale;
int ShangCaiTable;
int orderNum;//序号
Dish d;//菜品
int KouWei;
int portion;//份额(1/2/3代表小/中/大份)
int num;//数量
int getPrice() {
if(d!=null) {
int nowprice = d.getPrice(portion) * num;
return nowprice;
}
return 0;
}//计价,计算本条记录的价格
boolean check_record(String input,Table table,Menu menu) {
String[] record_input = input.split(" ");
if (!record_input[1].matches("\\d*"))
{
//System.out.println("点菜++++++++++++++++++++++++");
Dish dish;
dish = menu.searthDish(record_input[1]);
int orderNum=0,kouwei = 0,portion=0,num=0;
if (dish==null)
{System.out.println(record_input[1]+" does not exist"); return false;}
if (dish.specialty) {
orderNum = Integer.parseInt(record_input[0]);
kouwei = Integer.parseInt(record_input[2]);
portion = Integer.parseInt(record_input[3]);
num = Integer.parseInt(record_input[4]);
if (!dish.checkkouwei(kouwei)) {
return false;
}
}
else {
orderNum = Integer.parseInt(record_input[0]);
portion = Integer.parseInt(record_input[2]);
num = Integer.parseInt(record_input[3]);
}
DingCaiTale = table.num;
ShangCaiTable = table.num;
this.orderNum = orderNum;
d = dish;
this.portion = portion;
this.num = num;
KouWei = kouwei;
if(d!=null) System.out.println(orderNum+" "+record_input[1]+" "+getPrice());
} else if (record_input[1].matches("\\d*")) {
//ystem.out.println("代点菜++++++++++++++++++++++++");
Dish dish;
dish = menu.searthDish(record_input[1]);
int orderNum=0,ShangCaiTable=0,kouwei = 0,portion=0,num=0;
if (dish==null)
{System.out.println(record_input[1]+" does not exist"); return false;}
if (dish.specialty) {
orderNum = Integer.parseInt(record_input[0]);
kouwei = Integer.parseInt(record_input[3]);
portion = Integer.parseInt(record_input[4]);
num = Integer.parseInt(record_input[5]);
if (!dish.checkkouwei(kouwei)) {
return false;
}
}
else {
orderNum = Integer.parseInt(record_input[0]);
portion = Integer.parseInt(record_input[3]);
num = Integer.parseInt(record_input[4]);
}
DingCaiTale = table.num;
this.ShangCaiTable = ShangCaiTable;
this.orderNum = orderNum;
d = dish;
this.portion = portion;
this.num = num;
System.out.println(orderNum+" table "+DingCaiTale+" pay for table "+ShangCaiTable+" "+d.getPrice(portion)*num);
}
return true;
}
}
class Order {
ArrayList<Record> records = new ArrayList<>();
int laNum = 0;
int laTotal = 0;
int suanNum = 0;
int suanTotal = 0;
int tianNum = 0;
int tianTotal = 0;
int getTotalPrice() { //计算订单的总价
int sum = 0;
for(int i=0;i<records.size();i++) {
sum+=records.get(i).getPrice();
}
return sum;
}
void delARecordByOrderNum(int orderNum){ //根据序号删除一条记录
Record record = findRecordByNum(orderNum);
Dish dish;
if(record!=null) {
dish = findRecordByNum(orderNum).d;
switch (dish.classification) {
case 1 : {
laNum--;
laTotal -= record.num * record.KouWei;
}
case 2 : {
suanNum--;
suanTotal -= record.num * record.KouWei;
}
case 3 : {
tianNum--;
tianTotal -= record.num * record.KouWei;
}
default:
break;
}
findRecordByNum(orderNum).num = 0;
} else {
System.out.println("delete error;");
}
}
Record findRecordByNum(int orderNum){ //根据序号查找一条记录
for(int i=0;i<records.size();i++){
if(records.get(i).orderNum == orderNum){
return records.get(i);
}
}return null;
}
boolean check_record(String input,Table table,ArrayList<Integer> zhuohao,Menu menu,int ordercount) {
Record record = new Record();
if (record.check_record(input, table, menu)) {
switch (record.d.classification) {
case 1:
laNum += record.num;
laTotal += record.KouWei*record.num;
break;
case 2:
suanNum += record.num;
suanTotal += record.KouWei*record.num;
break;
case 3:
tianNum += record.num;
tianTotal += record.KouWei*record.num;
break;
}
}records.add(record);
return true;
}
}
class Table{
int num;
Order order = new Order();
int time;
int dayOfWeek;
String name;
String phoneNum;
public double GetDiscount(){
int LiuZhe_min = 103000;
int LiuZhe_max = 143000;
int BaZhe_min = 170000;
int BaZhe_max = 203000;
int WuZheKou_min = 100000;
int WuZheKou_max = 213000;
if (dayOfWeek>=1&&dayOfWeek<=5)
{
if(this.time>=LiuZhe_min&&this.time<=LiuZhe_max)
return 0.6;
else if (this.time>=BaZhe_min&&this.time<=BaZhe_max)
return 0.8;
else {
System.out.println("table " + num + " out of opening hours");
return -1;
}
}
else if (dayOfWeek>=6)
{
if(this.time>=WuZheKou_min&&this.time<=WuZheKou_max)
return 1;
else {
System.out.println("table " + num + " out of opening hours");
return -1;
}
}
return 0;
}
public int getOriginalPrice() {
return order.getTotalPrice();
}
public int getTotalDiscountedice() {
int sum = 0;
for(int i=0;i<order.records.size();i++)
{
if (order.records.get(i).d!=null) {
double zhekou = GetDiscount(), price_temp = 0;
price_temp = order.records.get(i).getPrice();
if (order.records.get(i).d.specialty && zhekou != 1) {
price_temp *= 0.7;
} else {
price_temp *= zhekou;
}
sum += (int) Math.round(price_temp);
}
}
return sum;
}
public boolean checkTable(String input) {
if (input.contains(" ")) {System.out.println("wrong format"); return false;}
String[] table_input = input.split(" ");
num = Integer.parseInt(table_input[1]);
name = table_input[3];
if (table_input[4].length()!=11) {System.out.println("wrong format"); return false;}
phoneNum = table_input[4];
if(!checkTableDate(table_input[5])) return false;
if(!checkTableTime(table_input[6])) return false;
return true;
}
private boolean checkTableDate(String input) {
String[] date_input = input.split("/");
int year = Integer.parseInt(date_input[0]);
int month = Integer.parseInt(date_input[1]);
int day = Integer.parseInt(date_input[2]);
String DAYTEMP = String.format("%04d/%02d/%02d", year, month, day);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.parse(DAYTEMP, formatter);
DayOfWeek DayOfWeek = localDate.getDayOfWeek();
this.dayOfWeek = DayOfWeek.getValue();
return true;
}
private boolean checkTableTime(String input) {
String[] time_input = input.split("/");
int xiaoshi = Integer.parseInt(time_input[0]);
int fenzhong = Integer.parseInt(time_input[1]);
int miao = Integer.parseInt(time_input[2]);
time = miao+fenzhong*100+xiaoshi*10000;
int LiuZhe_min = 103000;
int LiuZhe_max = 143000;
int BaZhe_min = 170000;
int BaZhe_max = 203000;
int WuZheKou_min = 100000;
int WuZheKou_max = 213000;
if (dayOfWeek>=1&&dayOfWeek<=5)
{
if(this.time>=LiuZhe_min&&this.time<=LiuZhe_max);
else if (this.time>=BaZhe_min&&this.time<=BaZhe_max);
else {
System.out.println("table " + num + " out of opening hours");
return false;
}
}
else if (dayOfWeek>=6)
{
if(this.time>=WuZheKou_min&&this.time<=WuZheKou_max);
else {
System.out.println("table " + num + " out of opening hours");
return false;
}
}
return true;
}
public void showkouwei()
{
Boolean flag = false;
//System.out.println(order.laNum);
String[] ladu = {" 不辣"," 微辣"," 稍辣"," 辣"," 很辣"," 爆辣"};
if (order.laNum != 0) {
System.out.print("川菜 ");
System.out.print(order.laNum);
//System.out.print(" *********"+(int) Math.round(order.laTotal*1.0/order.laNum)+"************** "+order.laTotal);
System.out.print(ladu[(int) Math.round(order.laTotal*1.0/order.laNum)]);
flag = true;
}
String[] suandu = {" 不酸"," 微酸"," 稍酸"," 酸"," 很酸"};
if (order.suanNum != 0) {
if (flag)
System.out.print(" ");
System.out.print("晋菜 ");
System.out.print(order.suanNum);
//System.out.print(" *********"+(int) Math.round(order.laTotal*1.0/order.laNum)+"************** "+order.laTotal);
System.out.print(suandu[(int) Math.round(order.suanTotal*1.0/order.suanNum)]);
flag = true;
}
String[] tiandu = {" 不甜"," 微甜"," 稍甜"," 甜"," 很甜"," 爆甜"};
if (order.tianNum != 0) {
if (flag)
System.out.print(" ");
System.out.print("浙菜 ");
System.out.print(order.tianNum);
//System.out.print(" *********"+(int) Math.round(order.laTotal*1.0/order.laNum)+"************** "+order.laTotal);
System.out.print(tiandu[(int) Math.round(order.tianTotal*1.0/order.tianNum)]);
}
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Menu menu = new Menu(); //一个menu,
Table table = null;
boolean dish_switch = true,order_switch = false,table_error_switch = false; //两个开关
int ordercount = 0;
List<Table> tables = new ArrayList<>();
ArrayList<Integer> zhuohao = new ArrayList<>();
String input = sc.nextLine();
while(!input.equals("end")) {
if (input.isEmpty()) System.out.println("wrong format");
else if (input.matches("^[\u4e00-\u9fa5].*")&&(!table_error_switch)) {
if (dish_switch) {
Dish dish = new Dish();
if (dish.checkdish(input))
menu.dishes.add(dish);
}
else
System.out.println("invalid dish");
}
else if(input.matches("^[a-zA-Z].*")) {
dish_switch = false;
if (input.startsWith("table"))
{
table = new Table();
if (table.checkTable(input))
{
zhuohao.add(Integer.parseInt(input.split(" ")[1]));
table_error_switch = false;
tables.add(table);
System.out.println("table "+table.num+": ");
order_switch = true;
ordercount = 0;
}
else {order_switch = false;table_error_switch = true;}
}
else {System.out.println("wrong format");}
}
else if (input.matches("^[0-9].*")&&order_switch) {
Record record = new Record();
if(input.matches(".*delete.*")) {
table.order.delARecordByOrderNum(Integer.parseInt(input.split(" ")[0]));
}
else if(table.order.check_record(input,table,zhuohao,menu,ordercount))
{
table.order.records.add(record);
if (input.split(" ").length==4) {ordercount++;}
}
}
input = sc.nextLine();}//while
ArrayList<String> renming = new ArrayList<>();
HashMap<String, Integer> priceMap = new HashMap<>();
for (Table tableout : tables) {
System.out.print("table "+tableout.num+": "+tableout.getOriginalPrice()+" "+tableout.getTotalDiscountedice()+" "); // 以getName()方法为例
tableout.showkouwei();
//String temp = tableout.name+" "+tableout.phoneNum;
int money = tableout.getTotalDiscountedice();
String name = tableout.name+" "+tableout.phoneNum;
//renming.add(temp);
priceMap.put(name, priceMap.getOrDefault(name, 0) + money);
}
for (String name : priceMap.keySet()) {
int totalPrice = priceMap.get(name);
renming.add(name + " " + totalPrice);
}
Collections.sort(renming);
for (String s : renming) {
System.out.println(s);
}
}
}
复杂度分析:
类图:
分析:
本次代码基于第四次重构的代码的一半的部分修改,得分90的原因是没书写带点菜处理的代码。
期中考试:
7-1 测验1-圆类设计
分数 10
作者 段喜龙
单位 南昌航空大学
创建一个圆形类(Circle),私有属性为圆的半径,从控制台输入圆的半径,输出圆的面积
输入格式:
输入圆的半径,取值范围为(0,+∞),输入数据非法,则程序输出Wrong Format,注意:只考虑从控制台输入数值的情况
输出格式:
输出圆的面积(保留两位小数,可以使用String.format(“%.2f”,输出数值)控制精度)
输入样例:
在这里给出一组输入。例如:
2.35
输出样例:
在这里给出相应的输出。例如:
17.35
import java.util.Scanner;
class Circle {
private double r;
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public void suanmianji()
{
if (this.r<=0)
System.out.println("Wrong Format");
else {
double mianji = 0;
mianji = Math.PI*r*r;
System.out.printf("%.2f",mianji);
}
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Circle circle = new Circle();
circle.setR(input.nextDouble());
circle.suanmianji();
}
}
7-2 测验2-类结构设计
分数 10
作者 段喜龙
单位 南昌航空大学
设计一个矩形类,其属性由矩形左上角坐标点(x1,y1)及右下角坐标点(x2,y2)组成,其中,坐标点属性包括该坐标点的X轴及Y轴的坐标值(实型数),求得该矩形的面积。
输入格式:
分别输入两个坐标点的坐标值x1,y1,x2,y2。
输出格式:
输出该矩形的面积值(保留两位小数)。
输入样例:
在这里给出一组输入。例如:
6 5.8 -7 8.9
输出样例:
在这里给出相应的输出。例如:
40.30
import java.nio.channels.Pipe;
import java.util.Scanner;
class Point {
private double x;
private double y;
public Point() {
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
class rectangle{
private Point topleftpoint;
private Point lowerrightpoint;
public rectangle(Point topleftpoint, Point lowerrightpoint) {
this.topleftpoint = topleftpoint;
this.lowerrightpoint = lowerrightpoint;
}
public rectangle() {
}
public Point getTopleftpoint() {
return topleftpoint;
}
public void setTopleftpoint(Point topleftpoint) {
this.topleftpoint = topleftpoint;
}
public Point getLowerrightpoint() {
return lowerrightpoint;
}
public void setLowerrightpoint(Point lowerrightpoint) {
this.lowerrightpoint = lowerrightpoint;
}
public double getlength()
{
return lowerrightpoint.getX()-topleftpoint.getX();
}
public double getheigher()
{
return topleftpoint.getY() - lowerrightpoint.getY();
}
public double getarea(){
return Math.abs(getlength()*getheigher());
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();
Point dianyi = new Point(x1,y1);
Point dianer = new Point(x2,y2);
rectangle rectangle = new rectangle(dianyi,dianer);
double area = rectangle.getarea();
System.out.printf("%.2f",area);
}
}
7-3 测验3-继承与多态
分数 20
作者 段喜龙
单位 南昌航空大学
将测验1与测验2的类设计进行合并设计,抽象出Shape父类(抽象类),Circle及Rectangle作为子类,类图如下所示:
image.png
试编程完成如上类图设计,主方法源码如下(可直接拷贝使用):
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 radiums = input.nextDouble();
Shape circle = new Circle(radiums);
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);
Rectangle rectangle = new Rectangle(leftTopPoint,lowerRightPoint);
printArea(rectangle);
break;
}
}
其中,printArea(Shape shape)方法为定义在Main类中的静态方法,体现程序设计的多态性。
输入格式:
输入类型选择(1或2,不考虑无效输入)
对应图形的参数(圆或矩形)
输出格式:
图形的面积(保留两位小数)
输入样例1:
1
5.6
输出样例1:
在这里给出相应的输出。例如:
98.52
输入样例2:
2
5.6
-32.5
9.4
-5.6
输出样例2:
在这里给出相应的输出。例如:
102.22
import java.util.Scanner;
import java.util.zip.DeflaterOutputStream;
abstract class Shape {
public Shape() {
}
public abstract double getarea();
}
class Circle extends Shape{
private double r;
public Circle(double r) {
this.r = r;
}
public Circle() {
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
@Override
public double getarea() {
double mianji = 0;
mianji = Math.PI*r*r;
//System.out.printf("%.2f",mianji);
return mianji;
}
}
class Point {
private double x;
private double y;
public Point() {
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
class Rectangle extends Shape{
private Point topleftpoint;
private Point lowerrightpoint;
public Rectangle(Point topleftpoint, Point lowerrightpoint) {
this.topleftpoint = topleftpoint;
this.lowerrightpoint = lowerrightpoint;
}
public Rectangle() {
}
public Point getTopleftpoint() {
return topleftpoint;
}
public void setTopleftpoint(Point topleftpoint) {
this.topleftpoint = topleftpoint;
}
public Point getLowerrightpoint() {
return lowerrightpoint;
}
public void setLowerrightpoint(Point lowerrightpoint) {
this.lowerrightpoint = lowerrightpoint;
}
public double getlength()
{
return lowerrightpoint.getX()-topleftpoint.getX();
}
public double getheigher()
{
return topleftpoint.getY() - lowerrightpoint.getY();
}
public double getarea(){
return Math.abs(getlength()*getheigher());
}
}
public class Main {
private static void printArea(Shape circle)
{
double area= circle.getarea();
System.out.printf("%.2f\n",area);
}
/*private static void printArea(Shape rectangle)
{
double area= rectangle.getarea();
System.out.printf("%.2f\n",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
//System.out.println("debug");
double radiums = input.nextDouble();
if(radiums<=0)
{
System.out.println("Wrong Format");
}
else
{
Shape circle = new Circle(radiums);
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);
Rectangle rectangle = new Rectangle(leftTopPoint,lowerRightPoint);
printArea(rectangle);
break;
}
}
}
7-4 测验4-抽象类与接口
分数 20
作者 段喜龙
单位 南昌航空大学
在测验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:结束输入)
输入图形所需参数
输出格式:
按升序排序输出列表中各图形的面积(保留两位小数),各图形面积之间用空格分隔。
输入样例:
在这里给出一组输入。例如:
1
2.3
2
3.2
3
6
5
1
2.3
0
输出样例:
在这里给出相应的输出。例如:
5.60 16.62 16.62
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.zip.DeflaterOutputStream;
abstract class Shape {
public Shape() {
}
public abstract double getarea();
}
class Circle extends Shape{
private double r;
public Circle(double r) {
this.r = r;
}
public Circle() {
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
@Override
public double getarea() {
double mianji = 0;
mianji = Math.PI*r*r;
//System.out.printf("%.2f",mianji);
return mianji;
}
}
class Point {
private double x;
private double y;
public Point() {
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
class Rectangle extends Shape{
private Point topleftpoint;
private Point lowerrightpoint;
public Rectangle(Point topleftpoint, Point lowerrightpoint) {
this.topleftpoint = topleftpoint;
this.lowerrightpoint = lowerrightpoint;
}
public Rectangle() {
}
public Point getTopleftpoint() {
return topleftpoint;
}
public void setTopleftpoint(Point topleftpoint) {
this.topleftpoint = topleftpoint;
}
public Point getLowerrightpoint() {
return lowerrightpoint;
}
public void setLowerrightpoint(Point lowerrightpoint) {
this.lowerrightpoint = lowerrightpoint;
}
public double getlength()
{
return lowerrightpoint.getX()-topleftpoint.getX();
}
public double getheigher()
{
return topleftpoint.getY() - lowerrightpoint.getY();
}
public double getarea(){
return Math.abs(getlength()*getheigher());
}
}
public class Main {
private static double printArea(Shape circle)
{
double area= circle.getarea();
return area;
//System.out.printf("%.2f\n",area);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
ArrayList<Double> 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(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);
Rectangle rectangle = new Rectangle(leftTopPoint,lowerRightPoint);
list.add(printArea(rectangle));
break;
}
choice = input.nextInt();
}
Collections.sort(list);
//list.sort(Comparator.naturalOrder());//正向排序
for(int i = 0; i < list.size(); i++) {
System.out.printf("%.2f ", list.get(i));
}
}
}
标签:return,期中考试,System,int,table,21207310,input,姜昊,out From: https://www.cnblogs.com/jianghao1125/p/17841067.html