oop个人总结第二集(
前言:
在第一集总结过后,我对于后续迭代的题目进行了重新设计,在之前设计失败的第二三次题目中,总结经验,向同学老师请教,也很好,有效的在答题判题程序设计题目的最后一次迭代设计成功,通过了所有测试。
后续发布了新的题目类型:家居强电电路模拟程序。
*我总结之前的经验,吸取先前的教训,通过家居强电电路模拟程序-1,部分通过家居强电电路模拟程序-2
这次题目集较以往不同的是,设计思路较之前会更加清晰,但会涉及更多有关物理电路相关的算法,但归根结底,前两次迭代比较简单,而且有了之前题目集的经验,也会更加得心应手,但是由于一些设计失误等原因,小部分测试点并未通过,这还需要我优化后续的设计思路。
设计与分析:
- 对于这次总结的第一题:答题判题程序-4
点击查看代码
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
abstract class Question {
private int num;
private String content;
private String standardAnswer;
private boolean isValid = true;//是否删除
private boolean isExist = true;
public Question(int num, String content, String standardAnswer) {
this.num = num;
this.content = content;
this.standardAnswer = standardAnswer;
}
public String getContent() {
return content;
}
public String getStandardAnswer() {
return standardAnswer;
}
public boolean isValid() {
return isValid;
}
public abstract int matchingStandardAnswers(String answer);
public void disabled() {
this.isValid = false;
}
public void nonExist() {
this.isExist = false;
}
public boolean isExist() {
return isExist;
}
}
//Z
class Choices_Question extends Question {
private int num;
private String content;
private String standardAnswer;
private boolean isValid = true;
public Choices_Question(int num, String content, String standardAnswer) {
super(num, content, standardAnswer);
this.num = num;
this.content = content;
this.standardAnswer = standardAnswer;
}
@Override
public int matchingStandardAnswers(String answer) {
if(answer.equals(standardAnswer)){
return 1;
}
String[] standardAnswers = this.standardAnswer.split(" ");
String[] userAnswers = answer.split(" ");
List<String> matchedAnswers = new ArrayList<>();
for (String standard_answer : standardAnswers) {
for (String Answer : userAnswers) {
if (standard_answer.equals(Answer)) {
matchedAnswers.add(Answer);
break;
}
}
}
boolean find = false;
for(String Answer : userAnswers){
find = false;
for(String standard_answer : standardAnswers){
if(Answer.equals(standard_answer)){
find = true;
break;
}
}
if(!find){
return 0;
}
}
if (matchedAnswers.size() == standardAnswers.length) {
return 1;
} else if (matchedAnswers.size() > 0) {
return 2;
} else {
return 0;
}
}
}
//N
class Filling_N extends Question {
private int num;
private String content;
private String standardAnswer;
private boolean isValid = true;
public Filling_N(int num, String content, String standardAnswer) {
super(num, content, standardAnswer);
this.num = num;
this.content = content;
this.standardAnswer = standardAnswer;
}
@Override
public int matchingStandardAnswers(String answer) {//判断是否符合标准答案
if (standardAnswer.equals(answer)) {
return 1;
} else {
return 0;
}
}
}
//K
class Filling_K extends Question {
private int num;
private String content;
private String standardAnswer;
private boolean isValid = true;
public Filling_K(int num, String content, String standardAnswer) {
super(num, content, standardAnswer);
this.num = num;
this.content = content;
this.standardAnswer = standardAnswer;
}
@Override
public int matchingStandardAnswers(String answer) {//判断是否符合标准答案
answer = answer.trim();
if (this.standardAnswer.equals(answer)) {
return 1;
} else if (this.standardAnswer.contains(answer)) {
return 2;
} else {
return 0;
}
}
}
class Question_in_Paper {
private Integer order_num; //在试卷中的顺序号
Question question;
private int question_score = 0;
private boolean isValid = true;
public Question_in_Paper(Integer order_num, Question question, int question_score) {
this.order_num = order_num;
this.question = question;
this.question_score = question_score;
}
public String getContent() {
return this.question.getContent();
}
public String getStandarAnswer() {
return this.question.getStandardAnswer();
}
public int getQuestion_score() {
return question_score;
}
public int judge_markAnswer(String answer) {//判断题目得分
if (this.question.matchingStandardAnswers(answer) != 0) {
return this.question_score;
} else {
return 0;
}
}
}
class TestPaper {
private int paper_num;//试卷号
private int questionTotal_num = 0;//题目数量
private int Total_score = 0;
private boolean isValid = true;
HashMap<Integer, Question_in_Paper> questions = new HashMap<>();
public TestPaper(int paper_num, int questionTotal_num) {
this.paper_num = paper_num;
this.questionTotal_num = questionTotal_num;
}
public void addQuestionToPaper(Integer order_num, Question_in_Paper question) {//增加题目
this.questions.put(order_num, question);
this.questionTotal_num++;
}
public int getQuestionTotal_num() {
return questionTotal_num;
}
}
class Answer {
Question_in_Paper question;
private String answer;
private int mark;
private int score = 0;//实际得分
public Answer() {
}
public Answer(String answer) {
this.answer = answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public void setScore(int score) {
this.score = score;
}
public Question_in_Paper getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
public void disable() {
}
public int getScore() {
return score;
}
public boolean isTRUE() {
return true;
}
}
class Answer_Paper {
private TestPaper paper;
private int answer_paper_num;
private boolean isValid = true;
private int answer_questions_num = 0;
HashMap<Integer, Answer> answers = new HashMap<>();
public Answer_Paper(int answer_paper_num) {
this.answer_paper_num = answer_paper_num;
}
public void disable() {
this.isValid = false;
}
public int getAnswer_paper_num() {
return answer_paper_num;
}
public void saveAnswer(int answer_order_num, Answer answer) {
this.answers.put(answer_order_num, answer);
this.answer_questions_num++;
}
public void setPaper(TestPaper testPaper) {
this.paper = testPaper;
}
public void OutputQ_As() {
for (int i = 1; i <= this.paper.getQuestionTotal_num(); i++) {
// if (paper.questions.get(i) != null) {
if(answers.get(i) != null){
if (paper.questions.get(i).question.isValid() && paper.questions.get(i).question.isExist()) {
System.out.print(paper.questions.get(i).question.getContent() + "~");
System.out.print(answers.get(i).getAnswer() + "~");
if (paper.questions.get(i).question.matchingStandardAnswers(answers.get(i).getAnswer()) == 1) {
System.out.println("true");
} else if (paper.questions.get(i).question.matchingStandardAnswers(answers.get(i).getAnswer()) == 2) {
System.out.println("partially correct");
} else {
System.out.println("false");
}
if (paper.questions.get(i).question.matchingStandardAnswers(answers.get(i).getAnswer()) != 0) {
if (paper.questions.get(i).question.matchingStandardAnswers(answers.get(i).getAnswer()) == 1) {
answers.get(i).setScore(paper.questions.get(i).getQuestion_score());
} else {
answers.get(i).setScore(paper.questions.get(i).getQuestion_score() / 2);
}
}
} else if (!paper.questions.get(i).question.isValid()) {
System.out.println("the question" + " " + i + " invalid~0");
} else if (!paper.questions.get(i).question.isExist()) {
System.out.println("non-existent question~0");
}
} else {
System.out.println("answer is null");
}
}
}
public void OutputScore() {
int totalScore = 0;
for (int i = 1; i <= this.paper.getQuestionTotal_num(); i++) {
int score;
if(answers.get(i)!=null){
score = answers.get(i).getScore();
} else {
score = 0;
}
System.out.print(" ");
System.out.print(score);
totalScore += score;
}
System.out.println("~" + totalScore);
}
public void Save_TestPaper() {
}
}
class Student {
private String id;
private String name;
private int answerSheet_num = 0;
HashMap<Integer, Answer_Paper> answer_papers = new HashMap<>();
TreeMap<Integer, Answer_Paper> sortedMap = new TreeMap<>();
HashMap<Integer, TestPaper> testPapers;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
public void setAnswerSheet_num() {
this.answerSheet_num++;
}
public void ergodicAnswerSheet(HashMap<Integer, TestPaper> testPapers) {
sortedMap.putAll(answer_papers);
this.testPapers = testPapers;
for (Map.Entry<Integer, Answer_Paper> entry : sortedMap.entrySet()) {
int paper_num = entry.getValue().getAnswer_paper_num();
if (testPapers.containsKey(paper_num)) {
entry.getValue().OutputQ_As();
System.out.print(id + " " + name + ":");
entry.getValue().OutputScore();
//score
} else {
System.out.println("The test paper number does not exist");
continue;
}
}
}
}
class Input {
ArrayList<String> lines = new ArrayList<>();
HashMap<Integer, Question> questions = new HashMap<>();
HashMap<Integer, TestPaper> testPapers = new HashMap<>();
HashMap<String, Student> students = new HashMap<>();
Output output;
public Input() {
}
public void addLines(String line) {
lines.add(line);
this.solve_question_InLine(line);//题目优先
}
public void solve_question_InLine(String line) {
Matcher matcherN = Pattern.compile("#N:").matcher(line);
Matcher matcherK = Pattern.compile("#K:").matcher(line);
Matcher matcherZ = Pattern.compile("#Z:").matcher(line);
if (matcherN.find()) saveQuestionN(line);
else if (matcherK.find()) saveQuestionK(line);
else if (matcherZ.find()) saveQuestionZ(line);
}
public void solveLine_Delete() {
for (String line : lines) {
Matcher matcherD = Pattern.compile("#D:").matcher(line);
if (matcherD.find()) saveDelete(line);
}
}
public void solveLine_Student() {
for (String line : lines) {
Matcher matcherX = Pattern.compile("#X:").matcher(line);
if (matcherX.find()) saveStudent(line);
}
}
public void solveLine_TestPaper() {
for (String line : lines) {
Matcher matcherT = Pattern.compile("#T:").matcher(line);
if (matcherT.find()) saveTestPaper(line);
}
}
public void solveLine_AnswerSheet() {
for (String line : lines) {
Matcher matcherS = Pattern.compile("#S:").matcher(line);
if (matcherS.find()) saveAnswerSheet(line);
}
}
public void saveQuestionN(String line) {
Matcher matcher_questionN = Pattern.compile("#N:(.*)#Q:(.*)#A:(.*)").matcher(line);
Matcher matcher_questionN_ = Pattern.compile("^#N: *(\\d+) *#Q:(.*)#A:(.*)").matcher(line);
if (!matcher_questionN_.find()) {
System.out.println("wrong format:" + line);
return;
}
if (matcher_questionN.find()) {
int number = Integer.parseInt(matcher_questionN.group(1).trim());
String content = matcher_questionN.group(2).trim();
String standardAnswer = matcher_questionN.group(3).trim();
Filling_N fill = new Filling_N(number, content, standardAnswer);
questions.put(number, fill);
return;
}
}
public void saveQuestionK(String line) {
Matcher matcher_questionK = Pattern.compile("#K:(\\d+)(\\s)*#Q:(.+)#A:(.+)").matcher(line);
Matcher matcher_questionK_ = Pattern.compile("^#K:(\\d+)(\\s)*#Q:(.+)#A:(.+)").matcher(line);
if (!matcher_questionK_.find()) {
System.out.println("wrong format:" + line);
return;
}
if (matcher_questionK.find()) {
int number = Integer.parseInt(matcher_questionK.group(1).trim());
String content = matcher_questionK.group(3).trim();
String standardAnswer = matcher_questionK.group(4).trim();
Filling_K fills = new Filling_K(number, content, standardAnswer);
questions.put(number, fills);
return;
}
}
public void saveQuestionZ(String line) {
Matcher matcher_questionZ = Pattern.compile("#Z:(\\d+)(\\s)*#Q:(.+)#A:(.+)").matcher(line);
Matcher matcher_questionZ_ = Pattern.compile("^#Z:(\\d+)(\\s)*#Q:(.+)#A:(.+)").matcher(line);
if (!matcher_questionZ_.find()) {
System.out.println("wrong format:" + line);
return;
}
if (matcher_questionZ.find()) {
int number = Integer.parseInt(matcher_questionZ.group(1).trim());
String content = matcher_questionZ.group(3).trim();
String standardAnswer = matcher_questionZ.group(4).trim();
Choices_Question choices_question = new Choices_Question(number, content, standardAnswer);
questions.put(number, choices_question);
return;
}
}
public void saveTestPaper(String line) {
Matcher matcherTestPaper = Pattern.compile("#T:(\\s+)?(\\d+)(\\s+)?").matcher(line);
Matcher matcherTestPaper_ = Pattern.compile("^#T:(\\s+)?(\\d+)(\\s+)?").matcher(line);
Matcher matcher_score = Pattern.compile("(\\d+)(-)(\\d+)").matcher(line);
if (!matcherTestPaper_.find()) {
System.out.println("wrong format:" + line);
return;
}
int paper_num = 0;
if (matcherTestPaper.find()) {
paper_num = Integer.parseInt(matcherTestPaper.group(2).trim());
}
int sum_score = 0;
int question_count = 0;
TestPaper testPaper = new TestPaper(paper_num, 0);
while (matcher_score.find()) {
int num = Integer.parseInt(matcher_score.group(1).trim());
int score = Integer.parseInt(matcher_score.group(3).trim());
question_count++;
if (questions.get(num) != null) {
Question new_question = questions.get(num);
Question_in_Paper question_in_paper = new Question_in_Paper(question_count, new_question, score);
testPaper.addQuestionToPaper(question_count, question_in_paper);
} else {
Question UnExisted_question = new Filling_N(0, "0", "0");
UnExisted_question.nonExist();
Question_in_Paper question_in_paper = new Question_in_Paper(question_count, UnExisted_question, score);
testPaper.addQuestionToPaper(question_count, question_in_paper);
}
sum_score += score;
}
testPapers.put(paper_num, testPaper);
if (sum_score != 100) {
System.out.print("alert: full score of test paper");
System.out.print(paper_num);
System.out.println(" is not 100 points");
}
}
public void saveAnswerSheet(String line) {
Matcher matcherS = Pattern.compile("#S: *(\\d+) +(\\d+)").matcher(line);
Matcher matcherS_ = Pattern.compile("^#S: *\\d+ +\\d+ *(.*?)$").matcher(line);
Matcher matcher_your_answer = Pattern.compile("#A:(\\s+)*(\\d+)(\\s+)*-(.*?)(\\s+)*(?=#A:|\\n|$)").matcher(line);//your answer
if (!matcherS_.find()) {
System.out.println("wrong format:" + line);
return;
}
if (matcherS.find()) {
int paper_num = Integer.parseInt(matcherS.group(1).trim());
String id = matcherS.group(2);
Answer_Paper answer_paper = new Answer_Paper(paper_num);
students.get(id).answer_papers.put(paper_num, answer_paper);
students.get(id).answer_papers.get(paper_num).setPaper(testPapers.get(paper_num));
while (matcher_your_answer.find()) {
int answer_num = Integer.parseInt(matcher_your_answer.group(2).trim());
String answer = matcher_your_answer.group(4);
Answer new_answer = new Answer(answer);
students.get(id).answer_papers.get(paper_num).saveAnswer(answer_num, new_answer);
}
}
}
public void saveStudent(String line) {
Matcher matcher_student = Pattern.compile("(\\d+)(\\s)([a-zA-Z]+)").matcher(line);
Matcher matcher_student_ = Pattern.compile("^#X: *( *\\d+ *\\w+ *-*)*$").matcher(line);
if (!matcher_student_.find()) {
System.out.println("wrong format:" + line);
return;
}
while (matcher_student.find()) {
String id = matcher_student.group(1).trim();
String name = matcher_student.group(3).trim();
Student student = new Student(id, name);
students.put(id, student);
}
}
public void saveDelete(String line) {
Matcher matcher_remove_question_ = Pattern.compile("^#D:(\\s*)N(\\s*)-(\\s*)(.+)$").matcher(line);
Matcher matcher_remove_question = Pattern.compile("N-(\\d+)").matcher(line);
if (!matcher_remove_question_.find()) {
System.out.println("wrong format:" + line);
return;
}
while (matcher_remove_question.find()) {
int num = Integer.parseInt(matcher_remove_question.group(1).trim());
questions.get(num).disabled();
}
}
public void output() {
this.output = new Output(this.questions, this.testPapers, this.students);
}
}
class Output {
HashMap<Integer, Question> questions;
HashMap<Integer, TestPaper> testPapers;
HashMap<String, Student> students;
TreeMap<String, Student> sortedMap = new TreeMap<>();
public Output(HashMap<Integer, Question> questions, HashMap<Integer, TestPaper> testPapers, HashMap<String, Student> students) {
this.questions = new HashMap<>(questions);
this.testPapers = new HashMap<>(testPapers);
this.students = new HashMap<>(students);
sortedMap.putAll(students);
}
public void output() {
for (Map.Entry<String, Student> entry : sortedMap.entrySet()) {//断点
Student student = entry.getValue();
student.ergodicAnswerSheet(this.testPapers);
}
}
}
public class Main {
public static void main(String[] args) {
Input input = new Input();
Scanner sc = new Scanner(System.in);
while (true) {
String line = sc.nextLine();
if (line.trim().equals("end")) {
break;
}
input.addLines(line);
}
input.solveLine_Delete();
input.solveLine_TestPaper();
input.solveLine_Student();
input.solveLine_AnswerSheet();
input.output();
input.output.output();
}
}
针对之前的错误案列,新增一些类,和处理方法,可以有效解决题目会出现的各种情况。
这次迭代相对之前新增了题目的题型,考察了继承和抽象类,我对Question类抽象,其中有抽象方法:判题方法,新增他的子类填空题,单选题,多选题等并具体,实现其不同的判题方法
代码逻辑:先从Main开始循环输入题目,试卷,答题,学生等信息,在Input中对其使用正则表达式进行分析输入信息,用不同的类储存信息
最后从Output开始遍历试卷,题目,答卷,输出判题的结果以及对应的分数。
代码分析:
代码中不乏错误处理:应对各种,题目,试卷,答案出错或缺少都会输出对应提示信息,避免程序崩溃,无法运行
代码设计了很多类,都实现了其单一职责,有效提高了代码的可读性,和理解性。
要说缺点:那就是在其中题目乱序输出的情况,我使用了较为复杂不通用的方法去读取题目信息,而并没有对其排序后再读取其中信息,如图
相对于其他同学,针对性的写一个排序方法,我这个通用性差,复用性差,如果后续再进行迭代,也许就死翘翘了T-T
- 对于家居强电电路模拟程序-1
点击查看代码
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// 设备类
abstract class Device {
int id;
double inVoltage = 0;
double outVoltage = 0;
public Device(int id) {
this.id = id;
}
public Device() {
}
public int getId() {
return id;
}
public double getInVoltage() {
return inVoltage;
}
}
abstract class ControlledDevice extends Device {
int id;
double inVoltage = 0;
double outVoltage = 0;
public ControlledDevice(int id) {
super(id);
}
public ControlledDevice() {
}
}//被控设备
abstract class ControllingDevice extends Device {
String id;
double inVoltage = 0;
double outVoltage = 0;
public ControllingDevice(int id) {
super(id);
}
public ControllingDevice() {
}
public abstract double getOutVoltage();
}//控制设备
// 开关类
class Switch extends ControllingDevice {
private int state = 0;
public Switch(int id) {
super(id);
}
public int getState() {
return state;
}
public void setState() {
if (state == 1) {
state = 0;
} else {
state = 1;
}
}
@Override
public double getOutVoltage() {
if(state == 1) {
return outVoltage;
} else {
return 0.0;
}
}
}
// 分档调速器类
class GearSpeedController extends ControllingDevice {
private int gear = 0;
public GearSpeedController(int id) {
super(id);
}
// 增加档位和减少档位的方法
public void upGear() {
if (gear < 3) {
gear++;
}
}
public void downGear() {
if (gear > 0) {
gear--;
}
}
public int getGear() {
return gear;
}
public void calculateVoltage(){
switch (gear){
case 0: outVoltage = 0;
break;
case 1: outVoltage = 0.3*220;
break;
case 2: outVoltage = 0.6*220;
break;
case 3: outVoltage = 0.9*220;
}
}
@Override
public double getOutVoltage() {
calculateVoltage();
return outVoltage;
}
}
// 连续调速器类
class ContinuousSpeedController extends ControllingDevice {
private double gear = 0;
public ContinuousSpeedController(int id) {
super(id);
}
public void setGear(double gear) {
this.gear = gear;
}
public double getGear() {
return gear;
}
public void calculateVoltage(){
this.outVoltage = gear*220.0;
}
public double getOutVoltage() {
calculateVoltage();
return outVoltage;
}
}
// 灯类
abstract class Light extends ControlledDevice {
public Light(int id) {
super(id);
}
// 具体实现亮度计算的方法
abstract double calculateBrightness(double voltage);
}
// 白炽灯类
class IncandescentLamp extends Light {
public IncandescentLamp(int id) {
super(id);
}
@Override
public double calculateBrightness(double voltage) {
if(voltage<=9){
return 0.0;
} else if(voltage>=220){
return 200.0;
} else{
return (5.0/7.0)*voltage+(300.0/7.0);
}
}
}
// 日光灯类
class DaylightLamp extends Light {
public DaylightLamp(int id) {
super(id);
}
@Override
public double calculateBrightness(double voltage) {
if(voltage==0){
return 0.0;
} else{
return 180.0;
}
}
}
// 风扇类
abstract class Fan extends ControlledDevice {
public Fan(int id) {
super(id);
}
// 具体实现转速计算的方法
abstract double calculateSpeed(double voltage);
}
// 吊扇类
class CeilingFan extends Fan {
public CeilingFan(int id) {
super(id);
}
@Override
public double calculateSpeed(double voltage) {
if(voltage<=80){
return 0.0;
} else if(voltage>=150){
return 360.0;
} else{
return ((voltage-80.0) / 70.0 *280.0)+80.0;
}
}
}
//串联电路类
class Series extends Device {
ArrayList <Device> devices = new ArrayList <>();
HashMap<Integer,Switch> switches = new HashMap<>();
HashMap<Integer,GearSpeedController> gearSpeedControllerHashMap = new HashMap<>();
HashMap<Integer,ContinuousSpeedController> continuousSpeedControllerHashMap = new HashMap<>();
HashMap<Integer,IncandescentLamp> incandescentLampHashMap = new HashMap<>();
HashMap<Integer,DaylightLamp> daylightLamps = new HashMap<>();
HashMap<Integer,CeilingFan> ceilingFans = new HashMap<>();
private double current;
private double voltage;
private double resistance;
public Series() {}
public Switch saveK(int id) {
Switch newSwitch = new Switch(id);
switches.put(id, newSwitch);
return newSwitch;
}
public GearSpeedController saveF(int id) {
GearSpeedController newGearSpeedController = new GearSpeedController(id);
gearSpeedControllerHashMap.put(id, newGearSpeedController);
return newGearSpeedController;
}
public ContinuousSpeedController saveL(int id) {
ContinuousSpeedController newContinuousSpeedController = new ContinuousSpeedController(id);
continuousSpeedControllerHashMap.put(id, newContinuousSpeedController);
return newContinuousSpeedController;
}
public IncandescentLamp saveB(int id) {
IncandescentLamp newIncandescentLamp = new IncandescentLamp(id);
incandescentLampHashMap.put(id, newIncandescentLamp);
return newIncandescentLamp;
}
public DaylightLamp saveR(int id) {
DaylightLamp newDaylightLamp = new DaylightLamp(id);
daylightLamps.put(id, newDaylightLamp);
return newDaylightLamp;
}
public CeilingFan saveD(int id) {
CeilingFan newCeilingFan = new CeilingFan(id);
ceilingFans.put(id, newCeilingFan);
return newCeilingFan;
}
}
class Input {
ArrayList<String> lines = new ArrayList<>();
Series series = new Series();//串联电路
Output output;
public Input() {
}
public void saveLines(String line) {
this.lines.add(line);
}
public void saveDevices() {
for (String line : this.lines) {
Matcher matcherDevices = Pattern.compile("\\[([A-Za-z]+)(\\d+)-(\\d+) ([A-Za-z]+)(\\d+)-(\\d+)]").matcher(line);
Matcher matcherE = Pattern.compile("\\[VCC ([A-Za-z]+)(\\d+)-(\\d+)]").matcher(line);
Matcher matcherG = Pattern.compile("\\[([A-Za-z]+)(\\d+)-(\\d+) GND]").matcher(line);
Matcher matcherSwitch = Pattern.compile("#K(\\d+)").matcher(line);
Matcher matcherGear = Pattern.compile("#F(\\d+)(.+)").matcher(line);
Matcher matcherContinuousSpeed = Pattern.compile("#L(\\d+):(.+)").matcher(line);
if (matcherE.find()) {
String device = matcherE.group(1);
int id = Integer.parseInt(matcherE.group(2));
int pin = Integer.parseInt(matcherE.group(3));
series.devices.add(judgeDevices(device, id));
}
if (matcherDevices.find()) {
String device1 = matcherDevices.group(1);
int id1 = Integer.parseInt(matcherDevices.group(2));
int pin1 = Integer.parseInt(matcherDevices.group(3));
String device2 = matcherDevices.group(4);
int id2 = Integer.parseInt(matcherDevices.group(5));
int pin2 = Integer.parseInt(matcherDevices.group(6));
series.devices.add(judgeDevices(device1, id1));
series.devices.add(judgeDevices(device2, id2));
}
if(matcherSwitch.find()){
series.switches.get(Integer.parseInt(matcherSwitch.group(1))).setState();
}
if(matcherGear.find()){
int id = Integer.parseInt(matcherGear.group(1));
if(matcherGear.group(2).equals("+")){
series.gearSpeedControllerHashMap.get(id).upGear();
}
if(matcherGear.group(2).equals("-")){
series.gearSpeedControllerHashMap.get(id).downGear();
}
}
if(matcherContinuousSpeed.find()){
int id = Integer.parseInt(matcherContinuousSpeed.group(1));
double gear = Double.parseDouble(matcherContinuousSpeed.group(2));
series.continuousSpeedControllerHashMap.get(id).setGear(gear);
}
}
}
public Device judgeDevices(String device, int id) {
switch (device) {
case "K":
return series.saveK(id);
case "F":
return series.saveF(id);
case "L":
return series.saveL(id);
case "B":
return series.saveB(id);
case "R":
return series.saveR(id);
default:
return series.saveD(id);
}
}
public void saveList(){
output = new Output(series.switches,series.ceilingFans,series.daylightLamps,series.incandescentLampHashMap,series.continuousSpeedControllerHashMap,series.gearSpeedControllerHashMap);
}
public void Output() {
saveList();
output.output();
}
}
class Output{
double TotalVoltage = 220.0;
HashMap<Integer,Switch> switches = new HashMap<>();
HashMap<Integer,GearSpeedController> gearSpeedControllerHashMap;
HashMap<Integer,ContinuousSpeedController> continuousSpeedControllerHashMap;
HashMap<Integer,IncandescentLamp> incandescentLampHashMap;
HashMap<Integer,DaylightLamp> daylightLamps ;
HashMap<Integer,CeilingFan> ceilingFans ;
TreeMap<Integer,Switch> sortedSwitches = new TreeMap<>();
TreeMap<Integer,GearSpeedController> sortedGearSpeedControllers = new TreeMap<>();
TreeMap<Integer,ContinuousSpeedController> sortedContinuousSpeedControllers = new TreeMap<>();
TreeMap<Integer,IncandescentLamp> sortedIncandescentLamps = new TreeMap<>();
TreeMap<Integer,DaylightLamp> sortedDaylightLamps = new TreeMap<>();
TreeMap<Integer,CeilingFan> sortedCeilingFans = new TreeMap<>();
public Output(HashMap<Integer, Switch> switches, HashMap<Integer, CeilingFan> ceilingFans, HashMap<Integer, DaylightLamp> daylightLamps, HashMap<Integer, IncandescentLamp> incandescentLampHashMap, HashMap<Integer, ContinuousSpeedController> continuousSpeedControllerHashMap, HashMap<Integer, GearSpeedController> gearSpeedControllerHashMap) {
this.switches = new HashMap<>(switches);
this.gearSpeedControllerHashMap = new HashMap<>(gearSpeedControllerHashMap);
this.continuousSpeedControllerHashMap = new HashMap<>(continuousSpeedControllerHashMap);
this.incandescentLampHashMap = new HashMap<>(incandescentLampHashMap);
this.daylightLamps = new HashMap<>(daylightLamps);
this.ceilingFans = new HashMap<>(ceilingFans);
sortedSwitches.putAll(switches);
sortedGearSpeedControllers.putAll(gearSpeedControllerHashMap);
sortedContinuousSpeedControllers.putAll(continuousSpeedControllerHashMap);
sortedIncandescentLamps.putAll(incandescentLampHashMap);
sortedDaylightLamps.putAll(daylightLamps);
sortedCeilingFans.putAll(ceilingFans);
}
public void output() {
outputK();
outputF();
outputL();
outputB();
outputR();
outputD();
}
private void outputK(){
for (Map.Entry<Integer,Switch> entry : sortedSwitches.entrySet()) {//断点
if(entry == null){
break;
}
Switch aSwitch = entry.getValue();
if(aSwitch.getState()==0){
System.out.println("@K" + aSwitch.getId() + ":turned on");
this.TotalVoltage = 0;
} else {
System.out.println("@K" + aSwitch.getId() + ":closed");
}
}
}
private void outputF(){
for (Map.Entry<Integer,GearSpeedController> entry : sortedGearSpeedControllers.entrySet()) {//断点
if(entry == null){
break;
}
GearSpeedController gearSpeedController = entry.getValue();
System.out.print("@F" + gearSpeedController.getId() + ":");
System.out.printf("%d\n", gearSpeedController.getGear());
gearSpeedController.calculateVoltage();
this.TotalVoltage = gearSpeedController.getOutVoltage();
}
}
private void outputL(){
for (Map.Entry<Integer,ContinuousSpeedController> entry : sortedContinuousSpeedControllers.entrySet()) {
if(entry == null){
break;
}
ContinuousSpeedController continuousSpeedController = entry.getValue();
System.out.print("@L" + continuousSpeedController.getId() + ":");
System.out.printf("%.2f\n",continuousSpeedController.getGear());
continuousSpeedController.calculateVoltage();
this.TotalVoltage = continuousSpeedController.getOutVoltage();
}
}
private void outputB(){
for(Map.Entry<Integer,IncandescentLamp> entry : sortedIncandescentLamps.entrySet()){
if(entry == null){
break;
}
IncandescentLamp incandescentLamp = entry.getValue();
System.out.print("@B" + incandescentLamp.getId() + ":" );
int integerPart = (int) incandescentLamp.calculateBrightness(TotalVoltage);
System.out.println(integerPart);
}
}
private void outputR(){
for(Map.Entry<Integer,DaylightLamp> entry : sortedDaylightLamps.entrySet()){
if(entry == null){break;}
DaylightLamp daylightLamp = entry.getValue();
System.out.print("@R" + daylightLamp.getId() + ":" );
System.out.printf("%.0f\n",daylightLamp.calculateBrightness(TotalVoltage));
}
}
private void outputD(){
for(Map.Entry<Integer,CeilingFan> entry : sortedCeilingFans.entrySet()){
if(entry == null){break;}
CeilingFan ceilingFan = entry.getValue();
System.out.print("@D" + ceilingFan.getId() + ":");
System.out.printf("%.0f\n",ceilingFan.calculateSpeed(TotalVoltage));
}
}
}
//并联电路类
class ParallelCircuit extends Device {
private String id;
private double current;
private double voltage;
private double resistance;
}
// 主程序
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Input input = new Input();
while (true) {
String line = sc.nextLine();
if (line.equals("end")) {
break;
}
input.saveLines(line);
}
input.saveDevices();
input.Output();
}
}
对于这次的电路只需要考虑,控制设备,受控设备,电路类,三种设备类的子类即可。
- 代码分析:
定义了如下几个类
Input:负责读取和处理输入数据,包括保存输入行、解析设备信息、保存设备到串联电路中,以及输出电路状态。
Output:类将设备按照类型排序,并分别输出它们的状态,如开关状态、调速器档位、灯的亮度和风扇的转速
Device类是所有设备的基类,包含设备的基本属性,如ID、输入电压和输出电压。
ControledDevice类,受控设备,包括几个用电器,如下:
Fan类:继承自ControledDevice类,有抽象方法,根据电压计算转速
CeilingFan类:继承自Fan类,实现类计算转速的方法。
Light类:继承自ControledDevice类,有抽象方法,根据电压计算灯泡亮度。
IncandescentLamp类和DaylightLamp类:继承自Light,分别实现计算亮度的方法。
ControlingDevice类:控制设备类,有调速器用于变压和开关控制电路
GearSpeedController类:分档调速器。ContinuousSpeedController类:连续调速器。
他们都有不同的方法可以调节电路的电压。
Switch类:开关,用于电路的联通。
Series类:串联电路类,包含各种设备。
-
代码逻辑:
首先由Input处理从Main输入的信息,并分析电路信息,储存电路信息,因为题目一暂时只有串联电路情况,所以储存到Series中,再针对控制设备的控制情况,对电路的情况进行更改,再由output分析Series中每个设备的电压信息,输出对应受控设备以及控制设备的信息情况。 -
不足之处:
1.Series 类中的 saveK、saveF、saveL 等方法有大量重复代码,可以考虑使用工厂模式来简化这些方法。
2.代码的结构较为复杂,有多个抽象类和具体实现类。可以考虑简化类结构,减少不必要的抽象。 -
总的来说,初步完成题目要求,但仍有许多不足之处需要改进。
-
对于 家居强电电路模拟程序-2:
-
定义了如下几个类
Input:负责读取和处理输入数据,包括保存输入行、解析设备信息、保存设备到串联电路中,以及输出电路状态。
Output:类将设备按照类型排序,并分别输出它们的状态,如开关状态、调速器档位、灯的亮度和风扇的转速
Device类是所有设备的基类,包含设备的基本属性,如ID、输入电压和输出电压。
ControledDevice类,受控设备,包括几个用电器,如下:
Fan类:继承自ControledDevice类,有抽象方法,根据电压计算转速
CeilingFan类和PedestalFan类:继承自Fan类,实现类计算转速的方法。
Light类:继承自ControledDevice类,有抽象方法,根据电压计算灯泡亮度。
IncandescentLamp类和DaylightLamp类:继承自Light,分别实现计算亮度的方法。
新增并联电路的情况,并新增几个用电器,
对于类进行类新增
需要新增并联电路类用于应对并联电路的情况
类图如下:
-
代码分析:
首先我在原先题目的基础上新增了题目需求的PedestalFan类继承于Fan类,再新增了电路和并联电路类用于处理和分析并联电路的信息,并有方法可以计算并联电路总电阻,再对被控设备ControledDevice增加电阻属性。
根据并联电路的添加,更改Input中识别电路信息的部分,新增可以匹配并联电路的正则表达式。 -
代码逻辑:
基本逻辑相较于前一道题目大致不变,在针对于并联电路做了具体分析,由分析串联电路,并联电路,再构造出一条基于串联电路的总电路,然后计算每一条分电路的总电阻,求和,得出总电路的总电阻,依据控制设备的得到调节之后的电压,遍历赋予每一条分电路各自的分压。最后输出时,先输出控制设备的信息再,再按照之前已经赋予的分压计算得出不同用电器的不同转速或者亮度。遍历所有总电路中已有用电器按照同样的方法输出即可。 -
不足之处:
在串联电路和并联电路中,有很多冗杂重复的代码,可以将他们整合成一个方法,然后调用这个方法就可以避免重复。
代码逻辑很复杂,在理解过程中有很大的麻烦,而且不利于代码的复用,很多一次性垃圾代码,这也导致了错误率大大提高,也让在排查未通过的测试点时,带来了很大的麻烦与困难。 -
未来改进:应该对两个电路类进行优化,减少重复代码,增强其可读性。
踩坑心得:
-
对于答题判题程序-4,其中多选题的判题方法需要十分严谨,例如需要考虑空白字符等,需要严格匹配。
还有踩坑的就是,之前对于题目的理解不够充分,不够深,所以大刀阔斧的对这道题目进行了重写,浪费了大量的时间和精力,这表明了,做好需求分析的重要性!!! -
对于 家居强电电路模拟程序-1
题目的设计思路十分清晰明了,基本上没有踩坑点,唯一要注意的就是,在针对四舍五入还是直接舍去小数位时,需要多多注意,要严格按照题目要求来输出相应的结果。 -
对于 家居强电电路模拟程序-2
题目复杂度上升,在设计并联电路类时,将其设计的过于复杂,导致代码可读性不高,同时又因为复杂方法过多,循环过多,if判断过多,让人头大,应该寻找更简便的代码思路来简化代码,以便后续迭代的编写顺利进行。
对于被控设备类可以统一实现获取电压的接口,也可以简化大量重复代码。
对于并联和串联电路,明显同属于电路,可以设计电路类,用于并联和串联的继承,这样就可以将重复冗杂的代码去除,得到更有利于理解的代码
总结,相较于之前的几次题目集,也大部分避免之前会经常犯的错误,但仍然不可避免的会在设计思路上有误差,因为总体设计思路上的问题,也就导致局部的编写错误,从而导致过于复杂。
改进建议:
在 家居强电电路模拟程序系列题目中,可以设计电路类,让串联电路,和并联电路继承于电路,找到两者的共通性,设计抽象方法和具体方法,发别实现即可,这样就可以避免在两者之间出现的相同且重复的代码,有限减少了代码量
总结:
有了第一次写题的经验,后续的题目也更加得心应手,在写题之前优先设计类图,思考类与类之间的关系,应该建立怎么样的关系保证之间的连接,从而实现题目需求。
在写完题目之后,也可以获得很多收获:
如广泛使用的oop的概念,如封装、继承和多态。通过定义基类和接口,以及创建具体的子类实现,可以理解如何构建一个具有层次结构的类体系。
继承和多态:通过继承基类 Device ,不同的电路组件类继承了共同的属性和方法,并通过重写方法实现特定的行为,有助于代码的简便和可拓展性
组合:在 Series 和 Parallel类中,通过将不同的电路组件组合在一起,可以构建更复杂的电路结构。
多种设计模式:Input 类中使用了工厂模式和策略模式(在方法中根据不同组件类型选择不同的行为),有助于理解设计模式在实际代码中的应用。
正则表达式的使用:Input 类中使用了正则表达式来解析输入字符串,提高匹配字符串的准确性和高效性
代码可维护性:代码中存在一些可维护性问题,如重复代码、复杂的条件判断等,这是要求我们在编写代码时要注重可维护性和可读性。
错误处理的重要性:代码中遍历时使用了不是null,所以在编程时应该考虑异常情况和错误处理,以提高程序的健壮性。
最后我希望接下来的课程能够再接再厉,学好oop不是梦!
posted on 2024-06-08 19:49 oblivioner 阅读(7) 评论(0) 编辑 收藏 举报