OOP第三次大作业
前言
前言的前言
快期末,也一直在等这次作业发布,我现在只能说终于等到了!!!跟上一个Blog的时间相隔比较大,内容也比较多,涉及范围也比较广7~11次小练习,废话不多说,直接开始吧。如果对我blog的内容有任何修正或者建议可以评论让我知道,谢谢你愿意点开我的blog并给出建议。
第七次作业
涉及知识点
类设计,正则表达式,LocalDate等
题量
依然是小小的一题,充满大大的代码量(其实也不大,主要是我之前的设计不好,在看了大佬的代码之后,模仿着重写了一次)
难度
依然是之前的菜单问题的迭代,有更多同学满分了,但我还是没能满分,深刻认识到了自己蒟蒻的本质。
第八次作业
涉及知识点
类设计,正则表达式等
题量
小小的一题,小小的码量(因为有内存限制)
难度
不是很难,具体表现为仅是“课程成绩统计程序”的第一次迭代,以及我第一次获得了满分。
第九次作业
涉及知识点
Map和Set的理解和应用
题量
仅一题,码量相当小,仅60行(虽然是我在各种方法里面极限压行的结果)
难度
不难,但是被去除多个空格的地方卡了好久,最后还是在大佬的帮助和提点下,才成功改对。
第十次作业
涉及知识点
Map的理解和应用,类设计,对于多态的理解。
题量
虽然数量是四题,但时间却花的比较少。
难度
不是特别难,在课程成绩统计程序-1中,我已经发现了我的代码设计不好,这次又重写了代码,花的时间比别人要多一些。
第十一次作业
涉及知识点
接口的理解和应用,类设计,正则表达式,自定义排序,Stack的模拟程序,对Override的理解和应用。
题量
5题,题量最大,涉及的知识点最多。
难度
总体来说不是很难,模拟的题目都给的比较清晰,但是课程成绩设计程序-3有一个测试点一直过不去,不太理解。(题外话,还好我上一次重写了代码,这次虽然修改了类设计,但是我主类里面修改还是比较少)
五次作业总结
总体来说还是感觉到了自己确确实实是在进步的,心态也更加沉稳了,第一次获得满分的时候也没有特别激动,至少没有第一次没有满分的时候那么难受。能力和心态上都有了不小的成长呢️。
设计与分析
写在前面
设计与分析中,主要放的是多次迭代的程序,其他题目的程序都比较小,就放在后面啦
7-1
源码数据
从上面的图可以看出:不但最大复杂度超标,我的最大深度和平均深度也超标了。看到我Waiter类里面的start方法,完全可以理解为啥会有这样的数据,if else疯狂叠加,最多的缩减高达14次QAQ。如果说这样丑陋的代码,能达到应有效果还尚且能以“黑猫白猫,能抓老鼠的就是好猫”来安慰自己,结果却是没能达到应有的效果,可读性也相当差,别说别人,我自己现在都看不懂我在写啥。
类图
源码
点击查看蒟蒻的垃圾千行代码
import java.util.*;
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
Waiter waiter = new Waiter();
waiter.start();
}
}
class Customer implements Comparable{
private String name;//客户的名字
private String phoneNumber;//客户的电话
public Customer() {
}
public Customer(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Override
public int compareTo(Object o) {
Customer c = (Customer) o;
if (c.getName().compareTo(this.getName()) > 0)
return -1;
else
return 1;
}
}
class Dish {
private String name;//菜品名称
private String style;//菜品口味
private int unit_price;//菜品基本价格
private boolean special = false;//是否是特色菜
public Dish() {
}
public Dish(String name, String style, int unit_price, boolean special) {
this.name = name;
this.style = style;
this.unit_price = unit_price;
this.special = special;
}
public boolean getSpecial() {
return special;
}
public void setSpecial(boolean special) {
this.special = special;
}
public int getPrice(int portion) {//计算价格
double price = 0.0;
if (portion == 1) {//小
price = unit_price;
} else if (portion == 2) {//中
price = unit_price * 1.5;
} else if (portion == 3) {//大
price = unit_price * 2;
}
return (int) (price + 0.5);
}
public String getName() {
return this.name;
}
public int getUnit_price() {
return this.unit_price;
}
public void setName(String name) {
this.name = name;
}
public void setUnit_price(int unit_price) {
this.unit_price = unit_price;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public boolean isSpecial() {
return special;
}
}
class Menu {
private final ArrayList<Dish> list = new ArrayList<>();//菜品数组,保存所有菜品信息
public Dish searthDish(String dishName) {//根据菜名查找
for (Dish dish : list) {
if (dishName.equals(dish.getName())) {
return dish;
}
}
return null;//没有找到
}
public Dish addDish(String dishName,String style, int unit_price, boolean special) {//增加一个菜品到list里面
Dish newDish = new Dish(dishName,style,unit_price,special);
list.add(newDish);
return newDish;
}
public void updateDish(String dishName, int unit_price, boolean special) {//重复时更新
for (Dish dish : list) {
if (dish.getName().equals(dishName)) {
dish.setSpecial(special);
dish.setUnit_price(unit_price);
}
}
}
public String getStyle(String name){
for(int i = 0;i < this.list.size();i ++){
if(list.get(i).getName().equals(name)){
return list.get(i).getStyle();
}
}
return null;
}
}
class MyDate {
private LocalDateTime date;
public MyDate() {
}
public MyDate(LocalDateTime date) {
this.date = date;
}
public LocalDateTime getDate() {
return date;
}
public void setMyDate(int year, int month, int day, int hh, int mm, int ss) {
this.date = LocalDateTime.of(year, month, day, hh, mm, ss);
}
public int getWeek() {
int week = this.date.getDayOfWeek().getValue();
return week;
}
}
class Order {
private final ArrayList<Record> list = new ArrayList<>();//保存订单上每一道记录
public ArrayList<Record> getList() {
return list;
}
public int getTotalPrice() {//计算总价
int total = 0;
for (Record record : list) {
total += record.getPrice();
}
return total;
}
public Record addARecord(int orderNum, Dish dish, int degree,int portion, int num ) {//添加菜品
Record newRecord = new Record(orderNum,dish,portion,degree,dish.getStyle(),num);
//list.add(newRecord);
return newRecord;
}
public Record addARecord(Record record) {//添加菜品
list.add(record);
return record;
}
public boolean delARecordByRecord(int orderNum) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getOrderNum() == orderNum) {
list.remove(i);
return true;
}
}
return false;
}
public boolean findRecordByNum(int orderNum) {
for (Record record : list) {
if (orderNum == record.getOrderNum()) {
return true;
}
}
return false;
}
}
class Record {
private int orderNum;//序号
private Dish dish = new Dish();//菜品
private int portion;//份额
private boolean spicy = false;//是不是川菜
private boolean acidity = false;//是不是晋菜
private boolean sweetness = false;//是不是浙菜
private int pungency = 0;//辣味程度
private int soul = 0;//酸味程度
private int sweet = 0;//甜味程度
private String style;//口味
private int num;//数量
private boolean self = true;//自己点的
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public boolean isSelf() {
return self;
}
public void setSelf(boolean self) {
this.self = self;
}
public int getPortion() {
return portion;
}
public void setPortion(int portion) {
this.portion = portion;
}
public int getPungency() {
return pungency;
}
public void setPungency(int pungency) {
this.pungency = pungency;
}
public int getSoul() {
return soul;
}
public void setSoul(int soul) {
this.soul = soul;
}
public int getSweet() {
return sweet;
}
public void setSweet(int sweet) {
this.sweet = sweet;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public boolean isSpicy() {
return spicy;
}
public void setSpicy(boolean spicy) {
this.spicy = spicy;
}
public boolean isAcidity() {
return acidity;
}
public void setAcidity(boolean acidity) {
this.acidity = acidity;
}
public boolean isSweetness() {
return sweetness;
}
public void setSweetness(boolean sweetness) {
this.sweetness = sweetness;
}
public Record() {
}
//有参构造
public Record(int orderNum, Dish dish, int portion, int degree, String style, int num) {
this.orderNum = orderNum;
this.dish = dish;
this.portion = portion;
if(style != null){//如果这个菜的口味不为空,就是特色菜
if(style.equals("川菜")){
this.pungency = degree;
}else if(style.equals("晋菜")){
this.soul = degree;
}else if(style.equals("浙菜")){
this.sweet = degree;
}
}
this.style = style;
this.num = num;
}
public int getPrice() {//计算价格
int price = 0;
if(isSelf()){
price = num * this.dish.getPrice((this.portion));
}
return price;
}
public int getOrderNum() {
return orderNum;
}
public void setOrderNum(int orderNum) {
this.orderNum = orderNum;
}
public Dish getDish() {
return dish;
}
public void setDish(Dish dish) {
this.dish = dish;
}
}
class Table {
private int tableNum;//桌号
private Order order = new Order();//点菜记录
private int totalPrice;//总价
private MyDate myDate = new MyDate();//日期
private Customer customer = new Customer();//顾客信息
private boolean hasSpicy = false;
private boolean hasAcidity = false;
private boolean hasSweetness = false;
public Table() {
}
public Table(int tableNum, MyDate myDate, Customer customer) {
this.tableNum = tableNum;
this.myDate = myDate;
this.customer = customer;
}
public Table(int tableNum, Order order) {
this.tableNum = tableNum;
this.order = order;
}
public MyDate getMyDate() {
return myDate;
}
public void setMyDate(MyDate myDate) {
this.myDate = myDate;
}
public boolean isHasSpicy() {
AveragePungency();
return hasSpicy;
}
public void setHasSpicy(boolean hasSpicy) {
this.hasSpicy = hasSpicy;
}
public boolean isHasAcidity() {
AverageSoul();
return hasAcidity;
}
public void setHasAcidity(boolean hasAcidity) {
this.hasAcidity = hasAcidity;
}
public boolean isHasSweetness() {
AverageSweet();
return hasSweetness;
}
public void setHasSweetness(boolean hasSweetness) {
this.hasSweetness = hasSweetness;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public MyDate getDate() {
return myDate;
}
public void setDate(MyDate myDate) {
this.myDate = myDate;
}
public int getTableNum() {
return tableNum;
}
public void setTableNum(int tableNum) {
this.tableNum = tableNum;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public int getTotalPrice() {
updateTotalPrice();
return totalPrice;
}
public void setTotalPrice(int totalPrice) {
this.totalPrice = totalPrice;
}
public void updateTotalPrice() {
this.totalPrice = order.getTotalPrice();
}
public int falseJudge() {
if (myDate.getWeek() <= 5 && myDate.getWeek() >= 1) {
if (myDate.getDate().getHour() >= 11 && myDate.getDate().getHour() <= 14) {
return 6;
} else if (myDate.getDate().getHour() >= 17 && myDate.getDate().getHour() <= 20) {
return 8;
} else if (myDate.getDate().getHour() == 10 && myDate.getDate().getMinute() >= 30) {
return 6;
} else if (myDate.getDate().getHour() == 20 && myDate.getDate().getMinute() <= 30) {
return 8;
} else if (myDate.getDate().getHour() == 14 && myDate.getDate().getMinute() <= 30) {
return 8;
} else {
return 0;
}
} else {
if (myDate.getDate().getHour() < 9) {
return 0;
} else if (myDate.getDate().getHour() >= 22) {
return 0;
} else if (myDate.getDate().getHour() == 9 && myDate.getDate().getMinute() < 30) {
return 0;
} else if (myDate.getDate().getHour() == 21 && myDate.getDate().getMinute() > 30) {
return 0;
} else {
return 10;
}
}
}
public int trueJudge() {
if (myDate.getWeek() <= 5 && myDate.getWeek() >= 1) {
if (myDate.getDate().getHour() >= 11 && myDate.getDate().getHour() <= 14) {
return 7;
} else if (myDate.getDate().getHour() >= 17 && myDate.getDate().getHour() <= 20) {
return 7;
} else if (myDate.getDate().getHour() == 10 && myDate.getDate().getMinute() >= 30) {
return 7;
} else if (myDate.getDate().getHour() == 20 && myDate.getDate().getMinute() <= 30) {
return 7;
} else if (myDate.getDate().getHour() == 14 && myDate.getDate().getMinute() <= 30) {
return 7;
} else {
return 0;
}
} else {
if (myDate.getDate().getHour() < 9) {
return 0;
} else if (myDate.getDate().getHour() >= 22) {
return 0;
} else if (myDate.getDate().getHour() == 9 && myDate.getDate().getMinute() < 30) {
return 0;
} else if (myDate.getDate().getHour() == 21 && myDate.getDate().getMinute() > 30) {
return 0;
} else {
return 10;
}
}
}
public int afterDiscount() {
int discountSpecial = trueJudge();
int discountNormal = falseJudge();
double total = 0.0;
for (int i = 0; i < this.getOrder().getList().size(); i++) {
if (this.getOrder().getList().get(i).getDish().getSpecial() == true) {
total += (int)(this.getOrder().getList().get(i).getPrice() * 1.0 * discountSpecial / 10.0 + 0.5);
} else {
total += (int)(this.getOrder().getList().get(i).getPrice() * 1.0 * discountNormal / 10.0 + 0.5);
}
}
return (int) (total + 0.5);
}
public int AveragePungency(){
double total = 0.0;
int sum = 0;
for(int i = 0;i < this.getOrder().getList().size();i ++){
if(this.getOrder().getList().get(i).isSpicy()){
hasSpicy = true;
sum += this.getOrder().getList().get(i).getNum();
total += this.getOrder().getList().get(i).getPungency() * this.getOrder().getList().get(i).getNum();
}
}
if(sum == 0){
return 0;
}
else {
return (int)((total * 1.0) / (sum * 1.0) + 0.5);
}
}
public int getPungencyNumber(){
int sum = 0;
for(int i = 0;i < this.getOrder().getList().size();i ++) {
if (this.getOrder().getList().get(i).isSpicy()) {
sum += this.getOrder().getList().get(i).getNum();
}
}
return sum;
}
public int AverageSoul(){
double total = 0.0;
int sum = 0;
for(int i = 0;i < this.getOrder().getList().size();i ++){
if(this.getOrder().getList().get(i).isAcidity()){
hasAcidity = true;
sum += this.getOrder().getList().get(i).getNum();
total += this.getOrder().getList().get(i).getSoul() * this.getOrder().getList().get(i).getNum();
}
}
if(sum == 0){
return 0;
}
else {
return (int)((total * 1.0) / (sum * 1.0) + 0.5);
}
}
public int getSoulNumber() {
int sum = 0;
for (int i = 0; i < this.getOrder().getList().size(); i++) {
if (this.getOrder().getList().get(i).isAcidity()) {
sum += this.getOrder().getList().get(i).getNum();
}
}
return sum;
}
public int AverageSweet(){
double total = 0.0;
int sum = 0;
for(int i = 0;i < this.getOrder().getList().size();i ++){
if(this.getOrder().getList().get(i).isSweetness()){
hasSweetness = true;
sum += this.getOrder().getList().get(i).getNum();
total += this.getOrder().getList().get(i).getSweet() * this.getOrder().getList().get(i).getNum();
}
}
if(sum == 0){
return 0;
}
else {
return (int)((total * 1.0) / (sum * 1.0) + 0.5);
}
}
public int getSweetNumber() {
int sum = 0;
for (int i = 0; i < this.getOrder().getList().size(); i++) {
if (this.getOrder().getList().get(i).isSweetness()) {
sum += this.getOrder().getList().get(i).getNum();
}
}
return sum;
}
}
class Waiter {
private ArrayList<Table> allTable = new ArrayList<>();
private ArrayList<Customer> customers = new ArrayList<>();
private boolean tableExist = true;
public Waiter() {
}
public void start(){
Scanner input = new Scanner(System.in);
String s;
boolean isPrint = false;
Menu menu = new Menu();
s = input.nextLine();
isPrint = false;
while (!s.equals("end") && s.split(" ").length <= 4){//输入菜单
String[] dish = s.split(" ");
if(menu.searthDish(dish[0]) != null){
if(dish.length == 2){
if(isNumber(dish[1])){
// menu.searthDish(dish[0]).setStyle(null);
// menu.searthDish(dish[0]).setSpecial(false);
menu.searthDish(dish[0]).setUnit_price(Integer.parseInt(dish[1]));
}else{
if(!isPrint){
isPrint = true;
System.out.println("wrong format");
}
}
}else if(dish.length == 4){
if(isNumber(dish[2])) {
// menu.searthDish(dish[0]).setStyle(dish[1]);
// menu.searthDish(dish[0]).setSpecial(true);
menu.searthDish(dish[0]).setUnit_price(Integer.parseInt(dish[2]));
}else{
if(!isPrint){
isPrint = true;
System.out.println("wrong format");
}
}
}
}else{
if(dish.length == 2){
if(isNumber(dish[1])) {
menu.addDish(dish[0], null, Integer.parseInt(dish[1]), false);
}else{
if(!isPrint){
isPrint = true;
System.out.println("wrong format");
}
}
}else if(dish.length == 4){
if(isNumber(dish[2])) {
menu.addDish(dish[0], dish[1], Integer.parseInt(dish[2]), true);
}else{
if(!isPrint){
isPrint = true;
System.out.println("wrong format");
}
}
}else{
if(!isPrint){
isPrint = true;
System.out.println("wrong format");
}
}
}
s = input.nextLine();
isPrint = false;
}
while (!s.equals("end")){
String[] tableMessage = s.split(" ");
if(tableMessage[0].equals("table")){//新的桌单
tableExist = true;
if(!isNumber(tableMessage[1])){
tableExist = false;
s = input.nextLine();
isPrint = false;
continue;
}
if(isCustomerName(tableMessage[3]) && isCustomerPhoneNumber(tableMessage[4])){
Customer customer = new Customer(tableMessage[3],tableMessage[4]);//顾客信息
if(isDate(tableMessage[5],tableMessage[6])){//时间是否合法
String[] arr1 = tableMessage[5].split("/");//将时间拆分
String[] arr2 = tableMessage[6].split("/");//hh,mm,ss
MyDate myDate = new MyDate();
myDate.setMyDate(Integer.parseInt(arr1[0]),Integer.parseInt(arr1[1]),Integer.parseInt(arr1[2]),Integer.parseInt(arr2[0]),Integer.parseInt(arr2[1]),Integer.parseInt(arr2[2]));
if(judgeTime(myDate) == 0){
System.out.println("table " + tableMessage[1] + " out of opening hours");
return;
}
customers.add(customer);//把顾客按字母顺序存储
Table table = new Table(Integer.parseInt(tableMessage[1]),myDate,customer);//存储餐桌信息
System.out.println("table " + table.getTableNum() + ": ");
s = input.nextLine();
isPrint = false;
while (s.split(" ").length == 4 || s.split(" ").length == 5 || s.split(" ").length == 2 || s.split(" ").length == 6 && tableExist){
String[] recordMessage = s.split(" ");
if(recordMessage[1].equals("delete")){//删除菜品
if(isNumber(recordMessage[0])){
if(table.getOrder().findRecordByNum(Integer.parseInt(recordMessage[0]))){
table.getOrder().delARecordByRecord(Integer.parseInt(recordMessage[0]));
}else {//找不到要删除的菜品
System.out.println("delete error;");
}
}else {
if(!isPrint){
isPrint = true;
System.out.println("wrong format");
}
}
}else if(recordMessage.length == 4){
if (menu.searthDish(recordMessage[1]) != null){
Dish dish;
Record record;
dish = menu.searthDish(recordMessage[1]);//获取这道菜的基本信息
//把点菜信息存到table
if(isNumber(recordMessage[0]) && isNumber(recordMessage[2]) && isNumber(recordMessage[3])){
record = table.getOrder().addARecord(Integer.parseInt(recordMessage[0]), dish, 0,Integer.parseInt(recordMessage[2]), Integer.parseInt(recordMessage[3]));
table.getOrder().addARecord(record);
System.out.println(record.getOrderNum() + " " + record.getDish().getName() + " " + record.getPrice());
}else {
if(!isPrint){
isPrint = true;
System.out.println("wrong format");
}
}
}else{
if(recordMessage[1].equals("川菜") || recordMessage[1].equals("晋菜") || recordMessage[1].equals("浙菜")){
if(!isPrint){
isPrint = true;
System.out.println("wrong format");
}
}else{
System.out.println(recordMessage[1] + " does not exist");
isPrint = true;
}
}
}else if(recordMessage.length == 5){
//判断各种度是否在范围内
if((menu.searthDish(recordMessage[1]).getStyle().equals("川菜") && isPungency(recordMessage[2])) ||
(menu.searthDish(recordMessage[1]).getStyle().equals("晋菜") && isSoul(recordMessage[2])) ||
(menu.searthDish(recordMessage[1]).getStyle().equals("浙菜") && isSweet(recordMessage[2]))) {
if (menu.searthDish(recordMessage[1]) != null){
Dish dish;
Record record;
dish = menu.searthDish(recordMessage[1]);//获取这道菜的基本信息
//把点菜信息存到table
record = table.getOrder().addARecord(Integer.parseInt(recordMessage[0]), dish, Integer.parseInt(recordMessage[2]),Integer.parseInt(recordMessage[3]), Integer.parseInt(recordMessage[4]));
if(dish.getStyle().equals("川菜")){
record.setSpicy(true);
}else if(dish.getStyle().equals("晋菜")){
record.setAcidity(true);
}else if(dish.getStyle().equals("浙菜")){
record.setSweetness(true);
}
table.getOrder().addARecord(record);
System.out.println(record.getOrderNum() + " " + record.getDish().getName() + " " + record.getPrice());
}else{//菜品不存在
isPrint = true;
System.out.println(recordMessage[1] + " does not exist");
}
} else{//不在范围内
if((menu.searthDish(recordMessage[1]).getStyle().equals("川菜"))){
System.out.println("spicy num out of range :" + recordMessage[2]);
}else if(menu.searthDish(recordMessage[1]).getStyle().equals("晋菜")){
System.out.println("acidity num out of range :" + recordMessage[2]);
}else if(menu.searthDish(recordMessage[1]).getStyle().equals("浙菜")){
System.out.println("sweetness num out of range :" + recordMessage[2]);
}
}
}else if(recordMessage.length == 6){
for (Table value : allTable) {
if (value.getTableNum() == Integer.parseInt(recordMessage[0])) {
//判断各种度是否在范围内
if((menu.searthDish(recordMessage[2]).getStyle().equals("川菜") && isPungency(recordMessage[3])) ||
(menu.searthDish(recordMessage[2]).getStyle().equals("晋菜") && isSoul(recordMessage[3])) ||
(menu.searthDish(recordMessage[2]).getStyle().equals("浙菜") && isSweet(recordMessage[3]))) {
if (menu.searthDish(recordMessage[2]) != null) {
Dish dish,dish1;//dish用来存本桌,dish1存被点的桌
Record record,record1;//record用来存本桌,record1存被点的桌
dish = menu.searthDish(recordMessage[2]);//获取这道菜的基本信息
dish1 = menu.searthDish(recordMessage[2]);
record = table.getOrder().addARecord(Integer.parseInt(recordMessage[1]), dish, Integer.parseInt(recordMessage[3]), Integer.parseInt(recordMessage[4]), Integer.parseInt(recordMessage[5]));
record1 = table.getOrder().addARecord(Integer.parseInt(recordMessage[1]), dish1, Integer.parseInt(recordMessage[3]), Integer.parseInt(recordMessage[4]),Integer.parseInt(recordMessage[5]));
record1.setSelf(false);
if (dish1.getStyle().equals("川菜")) {
record1.setSpicy(true);
} else if (dish1.getStyle().equals("晋菜")) {
record1.setAcidity(true);
} else if (dish1.getStyle().equals("浙菜")) {
record1.setSweetness(true);
}
table.getOrder().addARecord(record);
value.getOrder().addARecord(record1);
System.out.println(record.getOrderNum() + " table " + table.getTableNum() + " pay for table " + recordMessage[0] + " " + record.getPrice());
} else {//菜品不存在
isPrint = true;
System.out.println(recordMessage[1] + " does not exist");
}
}else{
if((menu.searthDish(recordMessage[1]).getStyle().equals("川菜"))){
System.out.println("spicy num out of range :" + recordMessage[2]);
}else if(menu.searthDish(recordMessage[1]).getStyle().equals("晋菜")){
System.out.println("acidity num out of range :" + recordMessage[2]);
}else if(menu.searthDish(recordMessage[1]).getStyle().equals("浙菜")){
System.out.println("sweetness num out of range :" + recordMessage[2]);
}
}
}
}
}else{
if(!isPrint){
isPrint = true;
System.out.println("wrong format");
}
}
s = input.nextLine();
isPrint = false;
}
allTable.add(table);//这桌信息存到list里面
}
}else {
if(!isPrint){
isPrint = true;
System.out.println("wrong format");
}
tableExist = false;
}
}
if(!tableExist){
s = input.nextLine();
isPrint = false;
}
}
printAllTable();
}
public boolean isCustomerName(String name){
if(name.length() <= 10){
return true;
} else {
return false;
}
}
public boolean isCustomerPhoneNumber(String number){
if(number.matches("^1(80|81|89|33|35|36)\\d{8}")){
return true;
}else {
return false;
}
}
public boolean isDate(String s1,String s2) {
boolean flagTime = false;//格式是否正确
boolean timeRight = true;//时间合法
String[] arr1 = s1.split("/");//将时间拆分
String[] arr2 = s2.split("/");//hh,mm,ss
if (arr1[0].matches("\\d{4}") && arr1[1].matches("\\d{1,2}") && arr1[2].matches("\\d{1,2}")
&& arr2[0].matches("\\d{1,2}") && arr2[1].matches("\\d{1,2}") && arr2[2].matches("\\d{1,2}")) {
if (arr1[0].charAt(0) != '0' && arr1[1].charAt(0) != '0' && arr1[2].charAt(0) != '0' &&
arr2[0].charAt(0) != '0') {
flagTime = true;
}
}
//判断日期是否合法
if (flagTime) {
int[] max_mon = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int year = Integer.parseInt(arr1[0]);
int month = Integer.parseInt(arr1[1]);
int day = Integer.parseInt(arr1[2]);
int hh = Integer.parseInt(arr2[0]);
int mm = Integer.parseInt(arr2[1]);
int ss = Integer.parseInt(arr2[2]);
//判断闰年
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
max_mon[2] = 29;
} else {
max_mon[2] = 28;
}
if (month < 1 || month > 12) {
timeRight = false;
} else if (day < 1 || day > max_mon[month]) {
timeRight = false;
} else if (hh > 24 || hh < 1) {
timeRight = false;
} else if (mm > 59 || mm < 0) {
timeRight = false;
} else if (ss > 59 || ss < 0) {
timeRight = false;
}
}
return timeRight && flagTime;
}
public void printAllTable(){
for(int i = 0;i < allTable.size();i ++){//遍历输出每一桌
/*for(int j = 0;j < allTable.get(i).getOrder().getList().size(); j ++){//输出每道菜
System.out.println(allTable.get(i).getOrder().getList().get(j).getOrderNum() + " " +
allTable.get(i).getOrder().getList().get(j).getDish().getName() + " " +
allTable.get(i).getOrder().getList().get(j).getPrice());
}*/
boolean flag = false;
System.out.print("table " + allTable.get(i).getTableNum() + ": " + allTable.get(i).getTotalPrice() + " " + allTable.get(i).afterDiscount());
//川菜(输入做判断)
if(printPungency(allTable.get(i))){
flag = true;
}
//晋菜(输入做判断)
if(printSoul(allTable.get(i))){
flag = true;
}
//浙菜(输入做判断)
if(printSweet(allTable.get(i))){
flag = true;
}
if(!flag){
System.out.println(' ');
}else{
System.out.println();
}
}
printCustomers();
}
public boolean printPungency(Table table){
if(table.isHasSpicy()){
System.out.print(" 川菜 " + table.getPungencyNumber());
if(table.AveragePungency() == 0){
System.out.print(" 不辣");
}else if(table.AveragePungency() == 1){
System.out.print(" 微辣");
}else if(table.AveragePungency() == 2){
System.out.print(" 稍辣");
}else if(table.AveragePungency() == 3){
System.out.print(" 辣");
}else if(table.AveragePungency() == 4){
System.out.print(" 很辣");
}else if(table.AveragePungency() == 5){
System.out.print(" 爆辣");
}
return true;
}
return false;
}
public boolean printSoul(Table table){
if(table.isHasAcidity()){
System.out.print(" 晋菜 " + table.getSoulNumber());
if(table.AverageSoul() == 0) {
System.out.print(" 不酸");
} else if(table.AverageSoul() == 1){
System.out.print(" 微酸");
}else if(table.AverageSoul() == 2){
System.out.print(" 稍酸");
}else if(table.AverageSoul() == 3){
System.out.print(" 酸");
}else if(table.AverageSoul() == 4){
System.out.print(" 很酸");
}
return true;
}
return false;
}
public boolean printSweet(Table table){
if(table.isHasSweetness()){
System.out.print(" 浙菜 " + table.getSweetNumber());
if(table.AverageSweet() == 0){
System.out.print(" 不甜");
}else if(table.AverageSweet() == 1){
System.out.print(" 微甜");
}else if(table.AverageSweet() == 2){
System.out.print(" 稍甜");
}else if(table.AverageSweet() == 3){
System.out.print(" 甜");
}
return true;
}
return false;
}
public void printCustomers(){
Collections.sort(customers);
for(int i = 0;i < customers.size();i ++){
int total = 0;
int sum = 0;
for(int j = 0;j < allTable.size();j ++){
if(allTable.get(j).getCustomer().getName().equals(customers.get(i).getName())){
sum += allTable.get(j).afterDiscount();
total ++;
}
}
i += total - 1;
System.out.println(customers.get(i).getName() + " " + customers.get(i).getPhoneNumber() + " " + sum);
}
}
public boolean isPungency(String s){
if(s.matches("[0-5]")){
return true;
}
return false;
}
public boolean isSoul(String s){
if(s.matches("[0-4]")){
return true;
}
return false;
}
public boolean isSweet(String s){
if(s.matches("[0-3]")){
return true;
}
return false;
}
public int judgeTime(MyDate myDate) {
if (myDate.getWeek() <= 5 && myDate.getWeek() >= 1) {
if (myDate.getDate().getHour() >= 11 && myDate.getDate().getHour() <= 14) {
return 7;
} else if (myDate.getDate().getHour() >= 17 && myDate.getDate().getHour() <= 20) {
return 7;
} else if (myDate.getDate().getHour() == 10 && myDate.getDate().getMinute() >= 30) {
return 7;
} else if (myDate.getDate().getHour() == 20 && myDate.getDate().getMinute() <= 30) {
return 7;
} else if (myDate.getDate().getHour() == 14 && myDate.getDate().getMinute() <= 30) {
return 7;
} else {
return 0;
}
} else {
if (myDate.getDate().getHour() < 9) {
return 0;
} else if (myDate.getDate().getHour() >= 22) {
return 0;
} else if (myDate.getDate().getHour() == 9 && myDate.getDate().getMinute() < 30) {
return 0;
} else if (myDate.getDate().getHour() == 21 && myDate.getDate().getMinute() > 30) {
return 0;
} else {
return 10;
}
}
}
public boolean isNumber(String s){
if(s.matches("^[1-9]\\d*$")){
return true;
}else{
return false;
}
}
}
浅说几句
这是菜单的最后一个迭代(我也是看到下一个题目集之后才知道的),我的菜单程序最终还是没能完全写好,仅以80多分草草收场,只留下了与“七大设计原则”背道而驰的,充满了垃圾代码的,看起来非常不适的程序。虽然比之前的代码有一些改进,但还是有存在很大的缺陷,从有多个“非零返回”这一点,就可以看出来,还存在比较严重的异常的情况,我猜测是把是数字字符串转化成整型时,存在非数字字符串的情况导致的异常。毕竟我是直接通过字符串数组来控制参数的,异常输入的时候,有非常大的可能导致异常情况的出现。
这个题目集结束了,之后,找满昏大佬要了代码看了一下,发现ta每一种正确输入的情况都是用正则表达式去匹配,其他情况就都是“Wrong format”,就很。我这才算是真正理解了,为什么大家都说“正则表达式可以极大地简化代码”。
7-1
开了新的迭代程序——课程成绩统计程序-1,闪亮登场(为我最终都没能完成的菜单程序默哀️️️)
源码数据
从上图可以比较明显的看到,除了最大复杂度,其他的数据都处于一个比较好的状态。从代码中不难发现,虽然有了比较大的改进,但是在输入学生信息进行判断存储时,存在大量的重复代码和各种判断,这种设计很明显是不好的,代码的复用性极差。
类图
源码
点击查看蒟蒻的两百行主方法代码
package OOP08;
import java.text.Collator;
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Courses courses = new Courses();
School school = new School();
String s;
while (input.hasNext()){
s = input.nextLine();
String[] arr = s.split(" ");
if(s.equals("end")){
school.outputClassStu();
courses.output();
school.outputClass();
return ;
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 必修 考察$")){
if(courses.searchCourse(arr[0]) == null){
System.out.println(arr[0] + " : course type & access mode mismatch");
}
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 必修$")){
Course course = new Course(arr[0],true);
courses.addCourse(course);
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} (选修|必修) 考试$")){
Course course = new Course(arr[0],true);
courses.addCourse(course);
} else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 选修 考察$")){
Course course = new Course(arr[0],false);
courses.addCourse(course);
}else if(s.matches("^\\d{8} [\\u4E00-\\u9FA5A-Za-z]{1,10} [\\u4E00-\\u9FA5A-Za-z]{1,10} ([0-9]\\d?|100) (100|[0-9]\\d?)")){
//输入学生信息,且考核方式为考试
Classroom classroom = new Classroom();
//判断班级是否存在,存在找到原来的班级,不存在新建
if(school.searchClassroom(Integer.parseInt(arr[0]) / 100) == null){
classroom.setNum(Integer.parseInt(arr[0]) / 100);
school.addClassroom(classroom);
} else{
classroom = school.searchClassroom(Integer.parseInt(arr[0]) / 100);
}
Course course = new Course(arr[2]);
//判断课程是否存在,存在设置成绩,不存在输出报错
if(courses.searchCourse(arr[2]) != null){
if(!courses.searchCourse(arr[2]).getWay()){
System.out.println(arr[0] + " " + arr[1] + " : access mode mismatch");
Student stu = new Student();
if(classroom.searchStudent(arr[0]) != null){
stu = classroom.searchStudent(arr[0]);
if(stu.searCourse(arr[2])){
stu.addCourse(course);
courses.searchCourse(arr[2]).addGrade(course.getReal(),course.getUsual(),course.getFinalGrade());
}
}else{
stu.setNum(arr[0]);
stu.setName(arr[1]);
if(stu.searCourse(arr[2])){
stu.addCourse(course);
courses.searchCourse(arr[2]).addGrade(course.getReal(),course.getUsual(),course.getFinalGrade());
}
classroom.addStu(stu);
}
}else {
course.setUsual(Integer.parseInt(arr[3]));
course.setFinalGrade(Integer.parseInt(arr[4]));
Student stu = new Student();
//判断该学生是否存在,存在找到原来的学生,不存在新建
if(classroom.searchStudent(arr[0]) != null){
stu = classroom.searchStudent(arr[0]);
if(stu.searCourse(arr[2])){
stu.addCourse(course);
courses.searchCourse(arr[2]).addGrade(course.getReal(),course.getUsual(),course.getFinalGrade());
}
}else{
stu.setNum(arr[0]);
stu.setName(arr[1]);
if(stu.searCourse(arr[2])){
stu.addCourse(course);
courses.searchCourse(arr[2]).addGrade(course.getReal(),course.getUsual(),course.getFinalGrade());
}
classroom.addStu(stu);
}
}
}else{
System.out.println(arr[2] + " does not exist");
Student stu = new Student(arr[0],arr[1]);
classroom.addStu(stu);
}
}else if(s.matches("^\\d{8} [\\u4E00-\\u9FA5A-Za-z]{1,10} [\\u4E00-\\u9FA5A-Za-z]{1,10} ([0-9]\\d?|100)")){
//输入学生信息,且考核方式为考察
Classroom classroom = new Classroom();
//同上
if(school.searchClassroom(Integer.parseInt(arr[0]) / 100) == null){
classroom.setNum(Integer.parseInt(arr[0]) / 100);
school.addClassroom(classroom);
} else{
classroom = school.searchClassroom(Integer.parseInt(arr[0]) / 100);
}
Course course = new Course(arr[2]);
if(courses.searchCourse(arr[2]) != null){
//判读该课程是否为选修,不是输出报错
if(courses.searchCourse(arr[2]).getWay()){
System.out.println(arr[0] + " " + arr[1] + " : access mode mismatch");
Student stu = new Student();
if(classroom.searchStudent(arr[0]) != null){
stu = classroom.searchStudent(arr[0]);
if(stu.searCourse(arr[2])){
stu.addCourse(course);
courses.searchCourse(arr[2]).addGrade(course.getReal(),course.getUsual(),course.getFinalGrade());
}
}else{
stu.setNum(arr[0]);
stu.setName(arr[1]);
if(stu.searCourse(arr[2])){
stu.addCourse(course);
courses.searchCourse(arr[2]).addGrade(course.getReal(),course.getUsual(),course.getFinalGrade());
}
classroom.addStu(stu);
}
}else{
Student stu = new Student();
course.setFinalGrade(Integer.parseInt(arr[3]));
if(classroom.searchStudent(arr[0]) != null){
stu = classroom.searchStudent(arr[0]);
if(stu.searCourse(arr[2])){
stu.addCourse(course);
courses.searchCourse(arr[2]).addGrade(course.getReal(),course.getUsual(),course.getFinalGrade());
}
}else{
stu.setNum(arr[0]);
stu.setName(arr[1]);
stu.addCourse(course);
courses.searchCourse(arr[2]).addGrade(course.getReal(),course.getUsual(),course.getFinalGrade());
classroom.addStu(stu);
}
}
}else{
System.out.println(arr[2] + " does not exist");
Student stu = new Student(arr[0],arr[1]);
classroom.addStu(stu);
}
} else{
System.out.println("wrong format");
}
}
}
}
class Course{
private final String name;//课程名称
private Boolean way;//true为考试,false为考察
private int real = -1;
private int usual = -1;
private int finalGrade = -1;
private int num = 0;
public Course(String name) {
this.name = name;
}
public Course(String name, Boolean way) {
this.name = name;
this.way = way;
}
public String getName() {
return name;
}
public Boolean getWay() {
return way;
}
public int getGrade() {
//计算成绩
if(usual != -1){
this.real = (int)(0.3 * usual + 0.7 * finalGrade);
}else{
this.real = finalGrade;
}
return real;
}
public int getNum() {
return num;
}
public int getUsual() {
return usual;
}
public void setUsual(int usual) {
this.usual = usual;
}
public int getFinalGrade() {
return finalGrade;
}
public void setFinalGrade(int finalGrade) {
this.finalGrade = finalGrade;
}
public int getReal() {
return real;
}
public void addGrade(int realGrade,int usual,int finalGrade){
//向课程中添加学生的成绩
if(finalGrade == -1){
return ;
}
if(this.getReal() == -1){
realGrade ++;
}
if(this.getUsual() == -1){
usual ++;
}
if(this.getFinalGrade() == -1){
finalGrade ++;
}
this.real += realGrade;
this.usual += usual;
this.finalGrade += finalGrade;
num ++;
}
public int getAverageUsual(){
//获取平均平时成绩
return this.getUsual() / this.getNum();
}
public int getAverageFinal(){
//获取平均考核成绩
return this.getFinalGrade() / this.getNum();
}
public int getAverageReal(){
//获取平均最后成绩
return this.getReal() / this.getNum();
}
}
class Courses {
private final TreeSet<Course> allCourse = new TreeSet<>((course, t1) -> {
Comparator<Object> compare = Collator.getInstance(Locale.CHINA);
return compare.compare(course.getName(), t1.getName());
});//构造一个按课程名称排序的HashSet
public void addCourse(Course course){
//添加课程
this.allCourse.add(course);
}
public Course searchCourse(String name){
//查找某课程是否存在
for (Course course : allCourse) {
if (course.getName().equals(name)) {
return course;
}
}
return null;
}
public void output(){
//课程信息的输出
for (Course course : allCourse) {
if (course.getReal() == -1) {
System.out.println(course.getName() + " has no grades yet");
} else {
if (course.getUsual() == -1) {
System.out.println(course.getName() + " " + course.getAverageFinal() + " " + course.getAverageReal());
} else {
System.out.println(course.getName() + " " + course.getAverageUsual() + " " + course.getAverageFinal() + " " + course.getAverageReal());
}
}
}
}
}
class Student{
private String num;//学号
private String name;//姓名
private final TreeSet<Course> courses= new TreeSet<>((course, t1) -> {
if(course.getGrade() > t1.getGrade()){
return -1;
}else{
return 1;
}
});//构造一个按课程名称排序的HashSet
public Student() {
}
public Student(String num, String name) {
this.num = num;
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public TreeSet<Course> getCourses() {
return courses;
}
public void addCourse(Course course){
this.courses.add(course);
}
public int getAverGrade(){
//计算平均成绩
int total = 0;
int num = 0;
for (Course course : courses) {
if (course.getGrade() != -1) {
num++;
total += course.getGrade();
}
}
//分母不能为0
if(num == 0){
return -1;
}else {
return total / num;
}
}
public void output(){
//学生信息输出
if(getAverGrade() != -1){
System.out.println(this.getNum() + " " + this.getName() + " " + this.getAverGrade());
}else{
System.out.println(this.getNum() + " " + this.getName() + " did not take any exams");
}
}
public boolean searCourse(String name){
for (Course courses : courses) {
Course course;
course = courses;
if (course.getName().equals(name)) {
return false;
}
}
return true;
}
}
class Classroom{
private final TreeSet<Student> students= new TreeSet<>(Comparator.comparing(Student::getNum));//构造一个按学号排序的HashSet
private int num;
private int total = -1;
private int courseNum = 0;
public Classroom() {
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getAverageGrade() {
for (Student student : students) {
for (Course course : student.getCourses()) {
if (total == -1) {
total = 0;
}
if (course.getReal() != -1) {
total += course.getReal();
courseNum++;
}
}
}
if(courseNum == 0){
return -1;
}else{
return total / courseNum;
}
}
public void addStu(Student student){
//添加学生
this.students.add(student);
}
public Student searchStudent(String number){
//查找某个学生
for (Student student : students) {
if (student.getNum().equals(number)) {
return student;
}
}
return null;
}
public void outputStudent(){
//输出班级内所有学生
for (Student student : students) {
student.output();
}
}
}
class School{
private final TreeSet<Classroom> classrooms = new TreeSet<>((classroom, t1) -> {
if(classroom.getNum() < t1.getNum()){
return -1;
}else {
return 1;
}
});//构造一个按班级号排序的HashSet
public Classroom searchClassroom(int classNumber){
//查找某个班级
for (Classroom value : classrooms) {
Classroom classroom;
classroom = value;
if (classroom.getNum() == classNumber) {
return classroom;
}
}
return null;
}
public void addClassroom(Classroom classroom){
//添加班级
this.classrooms.add(classroom);
}
public void outputClassStu(){
//按班级输出学校内所有学生信息
for (Classroom value : classrooms) {
Classroom classroom;
classroom = value;
classroom.outputStudent();
}
}
public void outputClass(){
//按班级输出学校内所有班级信息
for (Classroom value : classrooms) {
Classroom classroom;
classroom = value;
if (classroom.getAverageGrade() != -1) {
System.out.println(classroom.getNum() + " " + classroom.getAverageGrade());
} else {
System.out.println(classroom.getNum() + " has no grades yet");
}
}
}
}
浅说几句
这里模仿大佬的方法,用了正则表达式来进行匹配,明显逻辑清晰了很多,也减少了一些代码量。我一开始被卡在91分,最后3个测试点总是过不去,跟同学对拍,修改了几个bug之后还是没能顺利的通过测试点。最后发现是类似“高等数学A”这样的课程名称被判定为非法,换句话说,就是正则表达式只考虑了汉字和小写字母的,没有考虑到大写字母,修改之后就顺利满分了。值得一提的是,在对拍过程中,发现对于班级平均分有多种不同的计算结果,还都是满分的程序。蔡轲老师的测试点的普适性也太强了吧^ ^
7-3
源码数据
这个数据终于漂亮了一回,不枉我重写一次,把重复的代码都尽可能的封装成函数。
类图
源码
点击查看蒟蒻不那么垃圾的代码
package OOP10;
import java.text.Collator;
import java.util.*;
public class Main{
private static final TreeSet<Course> courses = new TreeSet<>((course, t1) -> {
Comparator<Object> compare = Collator.getInstance(Locale.CHINA);
return compare.compare(course.getName(), t1.getName());
});//构造一个按课程名称排序的HashSet
private static final TreeSet<Classroom> classrooms = new TreeSet<>((classroom, t1) -> {
if(classroom.getClassNumber() < t1.getClassNumber()){
return -1;
}else {
return 1;
}
});//构造一个按班级号排序的HashSet
private static final ArrayList<Choose> chooses = new ArrayList<>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s;
while (input.hasNext()){
s = input.nextLine();
String[] arr = s.split(" ");
if(s.equals("end")){
outputStudent();
outputCourse();
outputClass();
return ;
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 必修 考察$")){
if(searchCourseInCourses(arr[0]) == null){
System.out.println(arr[0] + " : course type & access mode mismatch");
}
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} (必修|选修) 实验$")){
if(searchCourseInCourses(arr[0]) == null){
System.out.println(arr[0] + " : course type & access mode mismatch");
}
}else if (s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} (必修|(必修 考试))$")) {
courses.add(new Course(arr[0],0,0));
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 选修 考试$")){
courses.add(new Course(arr[0],1,0));
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 选修 考察$")){
courses.add(new Course(arr[0],1,1));
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 实验 实验$")){
courses.add(new Course(arr[0],2,2));
}else if(s.matches("^\\d{8} [\\u4E00-\\u9FA5A-Za-z]{1,10} [\\u4E00-\\u9FA5A-Za-z]{1,10}( (100|[0-9]\\d?)){2}")){
//输入学生信息,考核方式为考试的课程
Classroom classroom = newClassroom(Integer.parseInt(arr[0]) / 100);
Course course = newCourse(Integer.parseInt(arr[0]),arr[1],arr[2],0);
addScore(Integer.parseInt(arr[3]),Integer.parseInt(arr[4]),course);
Student student = newStudent(arr[1],Integer.parseInt(arr[0]));
classroom.addStudent(student);
addCourseIntoStudent(student,course, course.getScore());
} else if(s.matches("^\\d{8} [\\u4E00-\\u9FA5A-Za-z]{1,10} [\\u4E00-\\u9FA5A-Za-z]{1,10} (100|[0-9]\\d?)")){
//输入学生信息,考核方式为考察的课程
Classroom classroom = newClassroom(Integer.parseInt(arr[0]) / 100);
Course course = newCourse(Integer.parseInt(arr[0]),arr[1],arr[2],1);
addScore(Integer.parseInt(arr[3]),course);
Student student = newStudent(arr[1],Integer.parseInt(arr[0]));
classroom.addStudent(student);
addCourseIntoStudent(student,course, course.getScore());
}else if(s.matches("^\\d{8} [\\u4E00-\\u9FA5A-Za-z]{1,10} [\\u4E00-\\u9FA5A-Za-z]{1,10} [4-9]( (100|0|[1-9]\\d?))*")){
//输入学生信息,考核方式为实验的课程
ArrayList<Integer> grade = new ArrayList<>();
for(int i = 4;i < arr.length;i ++){
grade.add(Integer.parseInt(arr[i]));
}
Classroom classroom = newClassroom(Integer.parseInt(arr[0]) / 100);
Course course = newCourse(Integer.parseInt(arr[0]),arr[1],arr[2],2);
addScore(grade,course);
Student student = newStudent(arr[1],Integer.parseInt(arr[0]));
classroom.addStudent(student);
if(grade.size() == Integer.parseInt(arr[3])){
addCourseIntoStudent(student,course, course.getScore());
}else{
System.out.println(arr[0] + " " + arr[1] + " : access mode mismatch");
}
}else{
System.out.println("wrong format");
}
}
}
public static Course searchCourseInCourses(String s){//查找某课程是否存在,存在复制后返回
for(Course course:courses){
if(course.getName().equals(s)){
return new Course(course.getName(),course.getCharacteristic(), course.getEvaluationWay());
}
}
return null;
}
public static boolean searchCourseInStudent(Student s,Course c){//判断某学生是否已经选择某课
for(Choose choose:chooses){
if(choose.getStudent().equals(s) && choose.getCourses().getName().equals(c.getName())){
return true;
}
}
return false;
}
public static Course newCourse(int studentNum,String studentName,String name,int evaluationWay){//学生进行选课
if(searchCourseInCourses(name) != null){//这个课程存在
if(accessMode(name,evaluationWay)){//课程性质和考察类型匹配
return searchCourseInCourses(name);
}else{
System.out.println( studentNum + " " + studentName + " : access mode mismatch");
}
}else{
System.out.println(name + " does not exist");
}
return new Course();
}
public static boolean accessMode(String name,int evaluationWay){//判断课程性质和给出的分数是否符合
for(Course course:courses){
if(course.getName().equals(name) && course.getEvaluationWay() == evaluationWay){
return true;
}
}
return false;
}
public static Classroom searchClassroom(int classNumber){//查找班级是否存在
for(Classroom classroom :classrooms){
if(classroom.getClassNumber() == classNumber){
return classroom;
}
}
return null;
}
public static Classroom newClassroom(int classNumber){//创建新的班级
if(searchClassroom(classNumber) != null){//该班级存在
for(Classroom classroom :classrooms){
if(classroom.getClassNumber() == classNumber){
return classroom;
}
}
}
Classroom classroom = new Classroom(classNumber);
classrooms.add(classroom);
return classroom;
}
public static Student searchStudent(int studentNumber,Classroom classroom){//查找某学生是否存在
for(Student s :classroom.getStudents()){
if(s.getStudentNumber() == studentNumber){
return s;
}
}
return null;
}
public static void addCourseIntoStudent(Student student,Course course,Score score){//把学生选课
if(!searchCourseInStudent(student,course) && !course.getName().equals("")){//如果该学生已选该课忽略,否则选课成功
chooses.add(new Choose(course,student,score));
}
}
public static Student newStudent(String name,int studentNumber){//创建新的学生信息
if(searchClassroom(studentNumber / 100) != null){
if(searchStudent(studentNumber,searchClassroom(studentNumber / 100)) != null){//这个学生存在
return searchStudent(studentNumber,searchClassroom(studentNumber / 100));
}
}
return new Student(name,studentNumber);
}
//在课程加入成绩的三种方式
public static void addScore(int finalGrade,Course course){
course.setScore(new InspectScore(finalGrade));
}
public static void addScore(int usualGrade,int finalGrade,Course course){
course.setScore(new TestScore(finalGrade,usualGrade));
}
public static void addScore(ArrayList<Integer> grades,Course course){
course.setScore(new ExperimentScore(grades));
}
public static void outputStudent(){//输出学生信息
for(Classroom classroom:classrooms){
for(Student student:classroom.getStudents()){
int sum = 0;
int total = 0;
for(Choose choose : chooses){
if(choose.getStudent().getStudentNumber() == student.getStudentNumber()){
if(choose.getCourses().getScore().calculateGrade() != -1){
sum += choose.getCourses().getScore().calculateGrade();
}
total ++;
}
}if(total == 0){
System.out.println(student.getStudentNumber() + " " + student.getName() + " did not take any exams");
} else {
System.out.println(student.getStudentNumber() + " " + student.getName() + " " + sum / total);
}
}
}
}
public static void outputCourse(){//输出课程信息
for(Course c:courses){
int sum = 0;
int total = 0;
int finalGrade = 0;
int usualGrade = 0;
for(Choose choose:chooses){
if(choose.getCourses().getName().equals(c.getName())){
if(choose.getCourses().getScore().calculateGrade() != -1){
sum += choose.getCourses().getScore().calculateGrade();
}
if(choose.getCourses().getScore().getNormalGrade() != -1){
usualGrade += choose.getCourses().getScore().getNormalGrade();
}
if(choose.getCourses().getScore().getFinalGrade() != -1){
finalGrade += choose.getCourses().getScore().getFinalGrade();
}
total ++;
}
}
if(total == 0){
System.out.println(c.getName() + " has no grades yet");
} else {
if (c.getEvaluationWay() == 0) {
System.out.println(c.getName() + " " + usualGrade / total + " " + finalGrade / total + " " + sum / total);
} else if(c.getEvaluationWay() == 1){
System.out.println(c.getName() + " " + finalGrade / total + " " + sum / total);
}else if(c.getEvaluationWay() == 2){
System.out.println(c.getName() + " " + sum / total);
}
}
}
}
public static void outputClass(){//输出班级信息
for(Classroom c:classrooms){
int sum = 0;
int total = 0;
for(Choose choose:chooses){
if(choose.getStudent().getStudentNumber() / 100 == c.getClassNumber()){
sum += choose.getScore().calculateGrade();
total ++;
}
}
if(total == 0) {
System.out.println(c.getClassNumber() + " has no grades yet");
}else{
System.out.println(c.getClassNumber() + " " + sum / total);
}
}
}
}
class Course{
private String name = new String();
private int characteristic = -1;//0为必修,1为选修,2为实验
private int evaluationWay = -1;//0为考试,1为考察,2为实验
private Score score;
public Course() {
}
public Course(String name, int characteristic, int evaluationWay) {
this.name = name;
this.characteristic = characteristic;
this.evaluationWay = evaluationWay;
}
public String getName() {
return name;
}
public int getCharacteristic() {
return characteristic;
}
public int getEvaluationWay() {
return evaluationWay;
}
public Score getScore() {
return score;
}
public void setScore(Score score) {
this.score = score;
}
}
class Student{
private String name;
private int studentNumber;
public Student() {
}
public Student(String name, int studentNumber) {
this.name = name;
this.studentNumber = studentNumber;
}
public String getName() {
return name;
}
public int getStudentNumber() {
return studentNumber;
}
}
class Classroom{
private int classNumber;
private final TreeSet<Student> students= new TreeSet<>(Comparator.comparing(Student::getStudentNumber));//构造一个按学号排序的HashSet
public Classroom() {
}
public Classroom(int classNumber) {
this.classNumber = classNumber;
}
public int getClassNumber() {
return classNumber;
}
public TreeSet<Student> getStudents() {
return students;
}
public void addStudent(Student student){
students.add(student);
}
}
abstract class Score {
private int finalGrade = -1;
private int normalGrade = -1;
private ArrayList<Integer> experimentGrades = new ArrayList<>();
public Score() {
}
public Score(int finalGrade) {
this.finalGrade = finalGrade;
}
public Score(int finalGrade, int normalGrade) {
this.finalGrade = finalGrade;
this.normalGrade = normalGrade;
}
public Score(ArrayList<Integer> experimentGrades) {
this.experimentGrades = experimentGrades;
}
public int getNormalGrade() {
return normalGrade;
}
public void setNormalGrade(int normalGrade) {
this.normalGrade = normalGrade;
}
public ArrayList<Integer> getExperimentGrades() {
return experimentGrades;
}
public void setExperimentGrades(ArrayList<Integer> experimentGrades) {
this.experimentGrades = experimentGrades;
}
public int getFinalGrade() {
return finalGrade;
}
public void setFinalGrade(int finalGrade) {
this.finalGrade = finalGrade;
}
public abstract int calculateGrade();
}
class TestScore extends Score {//考试成绩
public TestScore() {
super();
}
public TestScore(int finalGrade, int normalGrade) {
super(finalGrade, normalGrade);
}
@Override
public int getNormalGrade() {
return super.getNormalGrade();
}
@Override
public void setNormalGrade(int normalGrade) {
super.setNormalGrade(normalGrade);
}
@Override
public int calculateGrade(){
return (int)(getNormalGrade() * 0.3 + getFinalGrade() * 0.7);
}
@Override
public int getFinalGrade() {
return super.getFinalGrade();
}
@Override
public void setFinalGrade(int finalGrade) {
super.setFinalGrade(finalGrade);
}
}
class InspectScore extends Score {//考察成绩
public InspectScore() {
super();
}
public InspectScore(int finalGrade) {
super(finalGrade);
}
@Override
public int getNormalGrade() {
return super.getNormalGrade();
}
@Override
public void setNormalGrade(int normalGrade) {
super.setNormalGrade(normalGrade);
}
@Override
public ArrayList<Integer> getExperimentGrades() {
return super.getExperimentGrades();
}
@Override
public void setExperimentGrades(ArrayList<Integer> experimentGrades) {
super.setExperimentGrades(experimentGrades);
}
@Override
public int getFinalGrade() {
return super.getFinalGrade();
}
@Override
public void setFinalGrade(int finalGrade) {
super.setFinalGrade(finalGrade);
}
@Override
public int calculateGrade() {
return getFinalGrade();
}
}
class ExperimentScore extends Score{//实验成绩
public ExperimentScore() {
super();
}
public ExperimentScore(ArrayList<Integer> experimentGrades) {
super(experimentGrades);
}
@Override
public int getNormalGrade() {
return super.getNormalGrade();
}
@Override
public void setNormalGrade(int normalGrade) {
super.setNormalGrade(normalGrade);
}
@Override
public ArrayList<Integer> getExperimentGrades() {
return super.getExperimentGrades();
}
@Override
public void setExperimentGrades(ArrayList<Integer> experimentGrades) {
super.setExperimentGrades(experimentGrades);
}
@Override
public int getFinalGrade() {
return super.getFinalGrade();
}
@Override
public void setFinalGrade(int finalGrade) {
super.setFinalGrade(finalGrade);
}
@Override
public int calculateGrade() {
int t = 0;
for(Integer i:getExperimentGrades()){
t += i;
}
return t / getExperimentGrades().size();
}
}
class Choose{
private Course courses = new Course();
private Student student = new Student();
private Score score;
public Choose() {
}
public Choose(Course courses, Student student, Score score) {
this.courses = courses;
this.student = student;
this.score = score;
}
public Course getCourses() {
return courses;
}
public Student getStudent() {
return student;
}
public Score getScore() {
return score;
}
}
浅说几句
最应该说的,我觉得是有关search类的函数的返回值设置。根据题目主要有两种,一种是boolean类型的,判断是否存在;另一种是Object类型的,用来返回找到的对象。第二种又能根据不同的需求分成不同的类型,比如:你需要在原来的对象上进行修改,那么就返回引用;如果你是想要一个有原来数据的新对象,那就需要new一个存有原来数据的新对象。
7-2
源码数据
可以看到,这个代码的数据也是比较好看的,虽然这次在类设计上进行了大修改,但是得益于我上次的重写,在主方法的整体存储过程中没有太多的修改,和添加。主方法的修改主要是因为需要自定义权重,造成的在课程的分类上,和课程类中成绩的存储上的修改。
类图
源码
点击查看蒟蒻自以为尚可的代码
import java.text.Collator;
import java.util.*;
public class Main{
private static final TreeSet<Course> courses = new TreeSet<>((course, t1) -> {
Comparator<Object> compare = Collator.getInstance(Locale.CHINA);
return compare.compare(course.getName(), t1.getName());
});//构造一个按课程名称排序的HashSet
private static final TreeSet<Classroom> classrooms = new TreeSet<>((classroom, t1) -> {
if(classroom.getClassNumber() < t1.getClassNumber()){
return -1;
}else {
return 1;
}
});//构造一个按班级号排序的HashSet
private static final ArrayList<Choose> chooses = new ArrayList<>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s;
while (input.hasNext()){
s = input.nextLine();
String[] arr = s.split(" ");
if(s.equals("end")){
outputStudent();
outputCourse();
outputClass();
return ;
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 必修 考察$")){
if(searchCourseInCourses(arr[0]) == null){
System.out.println(arr[0] + " : course type & access mode mismatch");
}
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} (必修|选修) 实验 [4-9]( ([0-9]+[.][0-9]*))*")){
if(searchCourseInCourses(arr[0]) == null){
System.out.println(arr[0] + " : course type & access mode mismatch");
}
}else if (s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 必修 考试( ([0-9]+[.][0-9]*)){2}")) {
addCourseIntoMenu(3,arr,0,0,2);
} else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 选修 考试( ([0-9]+[.][0-9]*)){2}")){
addCourseIntoMenu(3,arr,1,0,2);
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 选修 考察$")){
addCourseIntoMenu(3,arr,1,1,1);
}else if(s.matches("^[\\u4E00-\\u9FA5A-Za-z]{1,10} 实验 实验 [4-9]( ([0-9]+[.][0-9]*))*")){
addCourseIntoMenu(4,arr,2,2,Integer.parseInt(arr[3]));
}else if(s.matches("^\\d{8} [\\u4E00-\\u9FA5A-Za-z]{1,10} [\\u4E00-\\u9FA5A-Za-z]{1,10}( (100|[0-9]\\d?)){2}")){
//输入学生信息,考核方式为考试的课程
Classroom classroom = newClassroom(Integer.parseInt(arr[0]) / 100);
Course course = newCourse(Integer.parseInt(arr[0]),arr[1],arr[2],0);
addScore(Integer.parseInt(arr[3]),Integer.parseInt(arr[4]),course);
Student student = newStudent(arr[1],Integer.parseInt(arr[0]));
classroom.addStudent(student);
addCourseIntoStudent(student,course, course.getScore());
} else if(s.matches("^\\d{8} [\\u4E00-\\u9FA5A-Za-z]{1,10} [\\u4E00-\\u9FA5A-Za-z]{1,10} (100|[0-9]\\d?)")){
//输入学生信息,考核方式为考察的课程
Classroom classroom = newClassroom(Integer.parseInt(arr[0]) / 100);
Course course = newCourse(Integer.parseInt(arr[0]),arr[1],arr[2],1);
addScore(Integer.parseInt(arr[3]),course);
Student student = newStudent(arr[1],Integer.parseInt(arr[0]));
classroom.addStudent(student);
addCourseIntoStudent(student,course, course.getScore());
}else if(s.matches("^\\d{8} [\\u4E00-\\u9FA5A-Za-z]{1,10} [\\u4E00-\\u9FA5A-Za-z]{1,10}( (100|0|[1-9]\\d?))*")){
//输入学生信息,考核方式为实验的课程
ArrayList<Integer> grade = new ArrayList<>();
for(int i = 3;i < arr.length;i ++){
grade.add(Integer.parseInt(arr[i]));
}
Classroom classroom = newClassroom(Integer.parseInt(arr[0]) / 100);
Course course = newCourse(Integer.parseInt(arr[0]),arr[1],arr[2],2);
addScore(grade,course);
Student student = newStudent(arr[1],Integer.parseInt(arr[0]));
classroom.addStudent(student);
if(searchCourseInCourses(arr[2]) != null) {
if (grade.size() == getExperimentScoreSize(arr[2])) {
addCourseIntoStudent(student, course, course.getScore());
} else {
System.out.println(arr[0] + " " + arr[1] + " : access mode mismatch");
}
}
}else{
System.out.println("wrong format");
}
}
}
public static boolean isWeightRight(ArrayList<Float> weight){
double sum = 0.0;
for(Float d:weight){
sum += d;
}
return Math.abs(sum - 1) <= 0.000001;
}
public static void addCourseIntoMenu(int begin,String[] arr,int characteristic,int evaluationWay,int size){
if(searchCourseInCourses(arr[0]) != null){
return;
}
ArrayList<Float> weight = new ArrayList<>();
for(int i = begin;i < arr.length;i ++){
weight.add(Float.parseFloat(arr[i]));
}
if(weight.size() == 0 && size == 1){
weight.add((float)1.0);
}
if(weight.size() == size){
if(isWeightRight(weight)){
Score score;
if(evaluationWay == 0){
score = new Score(new TestScore(weight));
}else if(evaluationWay == 1){
score = new Score(new InspectScore(weight));
}else{
score = new Score(new ExperimentScore(weight));
}
courses.add(new Course(arr[0], characteristic, evaluationWay, score));
}else{
System.out.println(arr[0] + " : weight value error");
}
}else{
System.out.println(arr[0] + " : number of scores does not match");
}
}
public static Course searchCourseInCourses(String s){//查找某课程是否存在,存在复制后返回
for(Course course:courses){
if(course.getName().equals(s)){
if(course.getEvaluationWay() == 0) {
return new Course(course.getName(), course.getCharacteristic(), course.getEvaluationWay(), new Score(new TestScore(course.getScore().getTestScore().getWeight())));
}else if(course.getEvaluationWay() == 1){
return new Course(course.getName(), course.getCharacteristic(), course.getEvaluationWay(), new Score(new InspectScore(course.getScore().getInspectScore().getWeight())));
}else if(course.getEvaluationWay() == 2){
return new Course(course.getName(), course.getCharacteristic(), course.getEvaluationWay(), new Score(new ExperimentScore(course.getScore().getExperimentScore().getWeight())));
}
}
}
return null;
}
public static int getExperimentScoreSize(String s){
for(Course course:courses){
if(course.getName().equals(s)){
return course.getScore().getExperimentScore().getWeight().size();
}
}
return 0;
}
public static boolean searchCourseInStudent(Student s,Course c){//判断某学生是否已经选择某课
for(Choose choose:chooses){
if(choose.getStudent().equals(s) && choose.getCourses().getName().equals(c.getName())){
return true;
}
}
return false;
}
public static Course newCourse(int studentNum,String studentName,String name,int evaluationWay){//学生进行选课
if(searchCourseInCourses(name) != null){//这个课程存在
if(accessMode(name,evaluationWay)){//课程性质和考察类型匹配
return searchCourseInCourses(name);
}else{
System.out.println( studentNum + " " + studentName + " : access mode mismatch");
}
}else{
System.out.println(name + " does not exist");
}
return new Course();
}
public static boolean accessMode(String name,int evaluationWay){//判断课程性质和给出的分数是否符合
for(Course course:courses){
if(course.getName().equals(name) && course.getEvaluationWay() == evaluationWay){
return true;
}
}
return false;
}
public static Classroom searchClassroom(int classNumber){//查找班级是否存在
for(Classroom classroom :classrooms){
if(classroom.getClassNumber() == classNumber){
return classroom;
}
}
return null;
}
public static Classroom newClassroom(int classNumber){//创建新的班级
if(searchClassroom(classNumber) != null){//该班级存在
for(Classroom classroom :classrooms){
if(classroom.getClassNumber() == classNumber){
return classroom;
}
}
}
Classroom classroom = new Classroom(classNumber);
classrooms.add(classroom);
return classroom;
}
public static Student searchStudent(int studentNumber,Classroom classroom){//查找某学生是否存在
for(Student s :classroom.getStudents()){
if(s.getStudentNumber() == studentNumber){
return s;
}
}
return null;
}
public static void addCourseIntoStudent(Student student,Course course,Score score){//把学生选课
if(!searchCourseInStudent(student,course) && !course.getName().equals("")){//如果该学生已选该课忽略,否则选课成功
chooses.add(new Choose(course,student,score));
}
}
public static Student newStudent(String name,int studentNumber){//创建新的学生信息
if(searchClassroom(studentNumber / 100) != null){
if(searchStudent(studentNumber,searchClassroom(studentNumber / 100)) != null){//这个学生存在
return searchStudent(studentNumber,searchClassroom(studentNumber / 100));
}
}
return new Student(name,studentNumber);
}
//在课程加入成绩的三种方式
public static void addScore(int finalGrade,Course course){
course.getScore().getInspectScore().getGrades().add(finalGrade);
}
public static void addScore(int usualGrade,int finalGrade,Course course){
course.getScore().getTestScore().getGrades().add(usualGrade);
course.getScore().getTestScore().getGrades().add(finalGrade);
}
public static void addScore(ArrayList<Integer> grades,Course course){
course.getScore().getExperimentScore().setGrades(grades);
}
public static void outputStudent(){//输出学生信息
for(Classroom classroom:classrooms){
for(Student student:classroom.getStudents()){
int sum = 0;
int total = 0;
for(Choose choose : chooses){
if(choose.getStudent().getStudentNumber() == student.getStudentNumber()){
if(choose.getCourses().getScore().calculateGrade(choose.getCourses().getEvaluationWay()) != -1){
sum += choose.getCourses().getScore().calculateGrade(choose.getCourses().getEvaluationWay());
}
total ++;
}
}if(total == 0){
System.out.println(student.getStudentNumber() + " " + student.getName() + " did not take any exams");
} else {
System.out.println(student.getStudentNumber() + " " + student.getName() + " " + sum / total);
}
}
}
}
public static void outputCourse(){//输出课程信息
for(Course c:courses){
int sum = 0;
int total = 0;
for(Choose choose:chooses){
if(choose.getCourses().getName().equals(c.getName())){
if(choose.getCourses().getScore().calculateGrade(choose.getCourses().getEvaluationWay()) != -1){
sum += choose.getCourses().getScore().calculateGrade(choose.getCourses().getEvaluationWay());
}
total ++;
}
}
if(total == 0){
System.out.println(c.getName() + " has no grades yet");
} else {
System.out.println(c.getName() + " " + sum / total);
}
}
}
public static void outputClass(){//输出班级信息
for(Classroom c:classrooms){
int sum = 0;
int total = 0;
for(Choose choose:chooses){
if(choose.getStudent().getStudentNumber() / 100 == c.getClassNumber()){
sum += choose.getScore().calculateGrade(choose.getCourses().getEvaluationWay());
total ++;
}
}
if(total == 0) {
System.out.println(c.getClassNumber() + " has no grades yet");
}else{
System.out.println(c.getClassNumber() + " " + sum / total);
}
}
}
}
class Course{
private String name = "";
private int characteristic = -1;//0为必修,1为选修,2为实验
private int evaluationWay = -1;//0为考试,1为考察,2为实验
private Score score = new Score();
public Course() {
}
public Course(String name, int characteristic, int evaluationWay, Score score) {
this.name = name;
this.characteristic = characteristic;
this.evaluationWay = evaluationWay;
this.score = score;
}
public String getName() {
return name;
}
public int getCharacteristic() {
return characteristic;
}
public int getEvaluationWay() {
return evaluationWay;
}
public Score getScore() {
return score;
}
}
class Student{
private String name;
private int studentNumber;
public Student() {
}
public Student(String name, int studentNumber) {
this.name = name;
this.studentNumber = studentNumber;
}
public String getName() {
return name;
}
public int getStudentNumber() {
return studentNumber;
}
}
class Classroom{
private int classNumber;
private final TreeSet<Student> students= new TreeSet<>(Comparator.comparing(Student::getStudentNumber));//构造一个按学号排序的HashSet
public Classroom() {
}
public Classroom(int classNumber) {
this.classNumber = classNumber;
}
public int getClassNumber() {
return classNumber;
}
public TreeSet<Student> getStudents() {
return students;
}
public void addStudent(Student student){
students.add(student);
}
}
class Score {
private TestScore testScore = new TestScore();
private InspectScore inspectScore = new InspectScore();
private ExperimentScore experimentScore = new ExperimentScore();
public Score() {
}
public Score(TestScore testScore) {
this.testScore = testScore;
}
public Score(InspectScore inspectScore) {
this.inspectScore = inspectScore;
}
public Score(ExperimentScore experimentScore) {
this.experimentScore = experimentScore;
}
public TestScore getTestScore() {
return testScore;
}
public InspectScore getInspectScore() {
return inspectScore;
}
public ExperimentScore getExperimentScore() {
return experimentScore;
}
public int calculateGrade(int evaluationWay){
ArrayList<Integer> grades = new ArrayList<>();
ArrayList<Float> weight = new ArrayList<>();
if(evaluationWay == 0){
grades = getTestScore().getGrades();
weight = getTestScore().getWeight();
}else if(evaluationWay == 1){
grades = getInspectScore().getGrades();
weight = getInspectScore().getWeight();
}else if(evaluationWay == 2){
grades = getExperimentScore().getGrades();
weight = getExperimentScore().getWeight();
}
if(grades.size() == 0){
return -1;
}else{
double sum = 0.0;
for(int i = 0;i < grades.size();i ++){
sum += grades.get(i) * weight.get(i);
}
return (int)(sum);
}
}
}
class TestScore{//考试成绩
private ArrayList<Integer> grades = new ArrayList<>();
private ArrayList<Float> weight = new ArrayList<>();
public TestScore() {
}
public TestScore(ArrayList<Float> weight) {
this.weight = weight;
}
public ArrayList<Integer> getGrades() {
return grades;
}
public ArrayList<Float> getWeight() {
return weight;
}
}
class InspectScore{//考察成绩
private ArrayList<Integer> grades = new ArrayList<>();
private ArrayList<Float> weight = new ArrayList<>();
public InspectScore() {
}
public InspectScore(ArrayList<Float> weight) {
this.weight = weight;
}
public ArrayList<Integer> getGrades() {
return grades;
}
public ArrayList<Float> getWeight() {
return weight;
}
}
class ExperimentScore{//实验成绩
private ArrayList<Integer> grades = new ArrayList<>();
private ArrayList<Float> weight = new ArrayList<>();
public ExperimentScore() {
}
public ExperimentScore(ArrayList<Float> weight) {
this.weight = weight;
}
public ArrayList<Integer> getGrades() {
return grades;
}
public void setGrades(ArrayList<Integer> grades) {
this.grades = grades;
}
public ArrayList<Float> getWeight() {
return weight;
}
}
class Choose{
private Course courses = new Course();
private Student student = new Student();
private Score score;
public Choose() {
}
public Choose(Course courses, Student student, Score score) {
this.courses = courses;
this.student = student;
this.score = score;
}
public Course getCourses() {
return courses;
}
public Student getStudent() {
return student;
}
public Score getScore() {
return score;
}
}
浅说几句
我这里用来处理权重的方式是在分数类里面,构建一个Double类型的ArrayList用来存储grades对应的权重。考察可看成权重为1.0,考试可看成权重分别为0.3,0.7(按输入存储)。
踩坑心得
写在前面
这次分析的题目集虽然多,但是前面也提到了,题目并不多,有些题目集甚至只要一题,在上面已经分析过了。下面就记录一下,我觉得比较有意思的题目和让人心痛的踩坑经历吧QAQ。
第九次作业
7-1
问题
虽然不是很理解,但是我被空格卡了好久,如下图。只把计数时的,分割字符串的正则从
String[] arr = s.split(" |\\{|}|;|\\.|\\(|\\)|\\[|]|,");
改成,一次匹配多个空格就通过了
String[] arr = s.split("\\s+|\\{|}|;|\\.|\\(|\\)|\\[|]|,|\"|\\\\");
下面是为了满足60行要求,极限压行下的丑陋产物
import java.util.*;
public class Main {
private static boolean flagAnnotation = true;//判断注释是否换行
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Map<String, Integer> map = new TreeMap<>();
Set<String> set = new HashSet<>(Arrays.asList("abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false",
"final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public",
"return", "strictfp", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while"));
for(String s:set){//对map进行初始化
map.put(s,0);
}
boolean flagExit = false;//判断是否输入了源代码
while (input.hasNext()){
String s = input.nextLine();
if(s.equals("exit")){
if(!flagExit){
System.out.println("Wrong Format");
}else output(map);
}else {
flagExit = true;
calculate(deleteAnnotation1(deleteAnnotation(deleteString(" " + s + " "))),map);//对读入的源代码进行处理
}
}
}
public static void output(Map<String, Integer> map){//输出map中value不为0的value和key
map.forEach((key, value ) ->{if(value != 0) System.out.println(value + "\t" + key);});
}
public static String deleteAnnotation(String s){//处理行注释
if(!s.contains("//")){
return s;
}else return s.split("//")[0];
}
public static String deleteAnnotation1(String s){//处理段注释
if(s.contains("*/")){
flagAnnotation = true;
}else if(s.contains("/*")){
flagAnnotation = false;
}else{
if(flagAnnotation){//代码不在段注释中
return s;
}else return " ";//这段代码在段注释内
}
if(!flagAnnotation){//出现/*的代码段,返回/*前的字符串
return s.split("/\\*|\\*/")[0];
}else return s.split("/\\*|\\*/")[1];//出现*/的代码段,返回*/后的字符串
}
public static String deleteString(String s){//删除字符串
if(!s.contains("\"")){
return s;
}else return s.split("\"")[0] + s.split("\"")[s.split("\"").length - 1];
}
public static void calculate(String s,Map<String,Integer> map){//分割处理好的字符串,统计关键字
for(String t : s.split("\\s+|\\{|}|;|\\.|\\(|\\)|\\[|]|,|\"|\\\\")){
if(map.containsKey(t)){
map.replace(t, map.get(t) + 1);
}
}
}
}
如果有懂的大佬麻烦在评论区或者私信告诉我,感激不尽
解释和心得
1、这题直接构造了一个存储了全部关键字的Set,再利用for-each,把Set中的元素压进TreeMap并进行value的初始化
2、Map的几种我喜欢的输出方式(均以本题输出为例):
1)利用map.forEach()和lambda表达式
map.forEach((key, value ) ->{
if(value != 0){
System.out.println(value + "\t" + key);
}
});
2)利用map.keySet(),获得一个存有key的Set
Set set = map.keySet();
for (Object o : set) {
if(map.get(o) != 0) {
System.out.println(map.get(o) + "\t" + o);
}
}
3)利用map.entrySet(),获得一个存有键值对的Set
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
if(entry.getValue() != 0) {
System.out.println(entry.getValue() + "\t" + entry.getKey());
}
}
第二次作业
7-2
问题
之前都是直接用TreeMap自定义比较器来完成排序的,对HashMap怎么排序还不太知道。遂搜索了一下,HashMap好像跟C++的Map非常像,因为不是线性存储(底层都是红黑树),所以不能直接用sort进行排序,只能压进别的线性容器里,再用sort进行排序。C++里面一般是把map中的元素压进pair类型的vector中(如果我说错了,麻烦指正,毕竟我也不是很会这玩意儿),那HashMap也可以相应的把Map中的元素压进entry类型的List里面,对List进行sort。
下面是我的代码
import java.util.*;
public class Main {
static HashMap<String, Student> students = new HashMap<>();//以学号为key,构造一个map用来存储学生信息
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while (input.hasNext()){
String s = input.nextLine();
if(s.equals("end")){
List<Map.Entry<String,Student> > list = mySort(students);
for(int i = 0;i < list.size();i ++){
System.out.println(list.get(i).getKey() + " " + list.get(i).getValue().getName() + " " + list.get(i).getValue().getGrade());
}
}else {
String[]arr = s.split(" ");
Student student = new Student(arr[1],Integer.parseInt(arr[2]));
students.put(arr[0],student);
}
}
}
public static List<Map.Entry<String,Student> > mySort(HashMap<String,Student> students){
List<Map.Entry<String,Student> > list = new ArrayList<Map.Entry<String,Student> >(students.entrySet());
list.sort(new Comparator<Map.Entry<String, Student>>() {
@Override
public int compare(Map.Entry<String, Student> stringStudentEntry, Map.Entry<String, Student> t1) {
return -stringStudentEntry.getKey().compareTo(t1.getKey());
}
});
return list;
}
}
class Student{
private String name;
private int grade = 0;
public Student() {
}
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
解释和心得
进行将HashMap压进List后,用sort进行的方法就是这个,这个题目最有价值的点就在这了
public static List<Map.Entry<String,Student> > mySort(HashMap<String,Student> students){
List<Map.Entry<String,Student> > list = new ArrayList<Map.Entry<String,Student> >(students.entrySet());
list.sort(new Comparator<Map.Entry<String, Student>>() {
@Override
public int compare(Map.Entry<String, Student> stringStudentEntry, Map.Entry<String, Student> t1) {
return -stringStudentEntry.getKey().compareTo(t1.getKey());
}
});
return list;
}
第十一次作业
7-4
问题
刚开始的pop是这样的
@Override
public Integer pop() {
if(t == 0){
return null;
}else{
return ans[t --];
}
}
如图,输出了奇怪的东西
解释和心得
结合下面完整代码的push写法,可以发现t的下标表示的是最后一个元素的下一个位置
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int n = input.nextInt();
ArrayIntegerStack arrayIntegerStack = new ArrayIntegerStack(n);
int m = input.nextInt();
for(int i = 0;i < m;i ++){
int t = input.nextInt();
System.out.println(arrayIntegerStack.push(t));
}
System.out.println(arrayIntegerStack.peek() + "," + arrayIntegerStack.empty() + "," + arrayIntegerStack.size());
System.out.println(Arrays.toString(arrayIntegerStack.getAns()));
int x = input.nextInt();
for(int i = 0;i < x;i ++){
System.out.println(arrayIntegerStack.pop());
}
System.out.println(arrayIntegerStack.peek() + "," + arrayIntegerStack.empty() + "," + arrayIntegerStack.size());
System.out.println(Arrays.toString(arrayIntegerStack.getAns()));
}
}
interface IntegerStack{
public Integer push(Integer item);//如果item为null,则不入栈直接返回null。如果栈满,也返回null。如果插入成功,返回item。
public Integer pop(); //出栈,如果为空,则返回null。出栈时只移动栈顶指针,相应位置不置为null
public Integer peek(); //获得栈顶元素,如果为空,则返回null.
public boolean empty(); //如果为空返回true
public int size(); //返回栈中元素个数
}
class ArrayIntegerStack implements IntegerStack{
private int n;
private int t = 0;
private Integer[] ans;
public ArrayIntegerStack(int n) {
this.n = n;
this.setAns(new Integer[n]);
}
public Integer[] getAns() {
return ans;
}
public void setAns(Integer[] ans) {
this.ans = ans;
}
@Override
public Integer push(Integer item) {
if(item == null || t == n){
return null;
}else{
ans[t ++] = item;
return item;
}
}
@Override
public Integer pop() {
if(t == 0){
return null;
}else{
return ans[-- t];
}
}
@Override
public Integer peek() {
if(t == 0){
return null;
}else{
return ans[t - 1];
}
}
@Override
public boolean empty() {
return t == 0;
}
@Override
public int size() {
return t;
}
}
所以,想要获得最后一个元素的位置,要先让t - 1再取值,可以改成如下:
@Override
public Integer pop() {
if(t == 0){
return null;
}else{
return ans[-- t];
}
}
改进建议
总的来说,还是能看到自己的进步的,但是还是有一些不足
1、代码的规范问题,注释比较少,可读性比较差,没有边写代码边注释的习惯,几乎每次都最后整体看一遍,再统一补注释,坏习惯更正任重而道远啊。
2、能有意识的进行类间关系的设计,但是设计还不够成熟,不能一开始就达到有比较好的拓展性和复用性。
总结
浅浅获得的一些知识
1、对Map的理解和应用
2、对线性容器,非线性容器排序
3、能比较熟练的运用正则表达式
需要进一步学习的知识
1、还是老生常谈的类设计,思维和熟练度还有待提高(还差得远呢)
一点小小的建议
1、教学理念(OBE)
构想很美好,但是好像现实没有那么美好,个人感觉没有完全达到教学目标
2、教学方法(边讲边练)
方法是好方法啊,就是每次练完,感觉没有给出答案,并不是指一定要给出一个具体的程序或者如何,我认为至少要给出一个思路或者大概处理的算法,或者说指出错误的处理方法之类的。至少要让我们能比较清楚的知道,我这样是对的还是错的。
3、教学组织(线上线下混合式教学)
线上教学时间比较短,对于一些相对比较难理解或者重要的部分,可能涉及的不是很全面。我觉得,线下教学的时候要对相应的线上教学内容做一定的解释和补充会比较好。
4、教学过程(PTA题目集驱动)
练习模式还是很好的,但是,我还是希望能开放通过偏低的题目的补题集。
5、教学模式(BOPPPS)
这个感觉还挺好的,没啥不好的
未完,可能再续……
一些题外话
最后一次OOP的blog,感觉自己成长了很多,好歹算是在OOP的路上迈出了第一步……总感觉感慨万千,但又说不出什么,没关系,我和OOP的故事才刚刚开始,以后的路还很长。最后以老师在课上提到的一句海子的诗做结,“以梦为马,以汗为泉,不忘初心,不负韶华”。
OOP第三次大作业的更多相关文章
- JAVA pta 前三次大作业回顾与分析
一.前言:总结三次题目集的知识点.题量.难度等情况 今年初次接触java,通过这三次大作业的练习,我对java有了一定的认识,相比于其他编程语言来说,java更复杂,要求也更严谨,需要掌握的知识也更多 ...
- oop 第三次作业 文件读写
oop第三次作业 GitHub 对于迟交我感到很抱歉 031602510 体会 这次的用到了之前的文件读写,传参 定义函数有返回值,使代码更加简洁.面向对象的程序设计,在面对函数多元的情况下,编程更加 ...
- #006 C语言大作业学生管理系统第三天
还差最后两部分 读取文件 恢复删除的学生信息 先学会处理文件的 知识点,再继续跟着视频做这个作业. 应该明天周六能把视频里手把手教的学生管理系统敲完 第二周尽量自己能完成C语言课本最后面那道学生管理系 ...
- python第三次周末大作业
''' s18第三周周末⼤作业 模拟博客园系统: 1. 启动程序, 显⽰菜单列表 菜单: 1. 登录 2. 注册 3. ⽂章 4. ⽇记 5. 退出 2. ⽤户输入选项, ⽂章和⽇记必须在登录后才可以 ...
- c++小学期大作业攻略(三)用户系统
Update at 2019/07/22 14:16 发现一个大坑,我们后期是打算用QSS统一堆样式进行美化的,于是我把之前对QLabel进行的setAlignment全部去掉了,打算统一丢进Qss里 ...
- 【作业】HansBug的前三次OO作业分析与小结
OO课程目前已经进行了三次的作业,容我在本文中做一点微小的工作. 第一次作业 第一次作业由于难度不大,所以笔者程序实际上写的也比较随意一些.(点击就送指导书~) 类图 程序的大致结构如下: 代码分析 ...
- 2016福州大学软件工程第三次个人作业-K米软件产品评测
K米软件测评个人作业结果统计如下: 评分标准: 按照栋哥布置的第三次个人作业--K米测评制定评分标准如下: 第一部分:调研.评测 下载并使用,描述最简单直观的个人第一次上手体验. 0.5 按照描述的b ...
- 数据库大作业--由python+flask
这个是项目一来是数据库大作业,另一方面也算是再对falsk和python熟悉下,好久不用会忘很快. 界面相比上一个项目好看很多,不过因为时间紧加上只有我一个人写,所以有很多地方逻辑写的比较繁琐,如果是 ...
- 程设大作业xjb写——魔方复原
鸽了那么久总算期中过[爆]去[炸]了...该是时候写写大作业了 [总不能丢给他们不会写的来做吧 一.三阶魔方的几个基本定义 ↑就像这样,可以定义面的称呼:上U下D左L右R前F后B UD之间的叫E,LR ...
- 第三次个人作业——关于K米(Andorid)的案例分析
第三次个人作业--关于K米(Andorid)的案例分析 1.K米简介 官方网址:http://www.ktvme.com/ 2.评测 2.1.上手体验 带着找bug的心态,兴致勃勃地开始体验 K米.打 ...
随机推荐
- vue3组合式API介绍
为什么要使用Composition API? 根据官方的说法,vue3.0的变化包括性能上的改进.更小的 bundle 体积.对 TypeScript 更好的支持.用于处理大规模用例的全新 API,全 ...
- 前端js几种加密/解密方法
https://www.jianshu.com/p/4c236d83ea04 https://blog.csdn.net/guxingsheng/article/details/84451573 vu ...
- [C++基础入门] 8、结构体
文章目录 8 结构体 8.1 结构体基本概念 8.2 结构体定义和使用 8.3 结构体数组 8.4 结构体指针 8.5 结构体嵌套结构体 8.6 结构体做函数参数 8.7 结构体中 const使用场景 ...
- Redis缓存穿透、击穿、雪崩
文章目录 缓存穿透 缓存雪崩 缓存击穿 代码实战部分 缓存击穿实战代码封装 缓存穿透解决 Redis目前是非常流行的缓存数据库,缓存穿透.缓存击穿.缓存雪崩是常见的面试题,也是非常重要的问题. 缓存穿 ...
- 【Redis】Setninel 哨兵机制
一.Sentinel 哨兵工作原理 Redis在2.6+以后引入哨兵机制,在2.8版本后趋于稳定状态,在生产环境中建议使用2.8版本以上的sentinel服务.sentinel集群用于监控redis集 ...
- Yolov5 根据自己的需要更改 预测框box和蒙版mask的颜色
1.首先找到项目中 utils/plots.py 文件,打开该代码 将原来的 Colors类注释掉(或删掉),改成如下Colors类 class Colors: def __init__(self): ...
- #Python基础 DateFrame 查看数据信息
一:导入案例数据及X-MIND 二:实例 2.1 显示摘要信息 2.2显示描述性统计信息 2.3显示 前后n行 2.4显示索引.列信息 2.5显示每列的数据类型
- Nginx Web快速入门
Nginx Web快速入门 目录 Nginx Web快速入门 Nginx概述 为什么选择Nginx服务 Nginx的应用场景 源码安装nginx Yum安装nginx Nginx相关命令总结 Ngin ...
- 2023-03-08:x265的视频编码器,不用ffmpeg,用libx265.dll也行。请用go语言调用libx265.dll,将yuv文件编码成h265文件。
2023-03-08:x265的视频编码器,不用ffmpeg,用libx265.dll也行.请用go语言调用libx265.dll,将yuv文件编码成h265文件. 答案2023-03-08: 使用 ...
- 2022-03-26:给定一个无向图, 从任何一个点x出发,比如有一条路径: x -> a -> b -> c -> y, 这条路径上有5个点并且5个点都不一样的话,我们说(x,a,b,c,y)是一条
2022-03-26:给定一个无向图, 从任何一个点x出发,比如有一条路径: x -> a -> b -> c -> y, 这条路径上有5个点并且5个点都不一样的话,我们说(x ...