前三次大作业博客总结

orangecookie / 2024-04-22 / 原文

第1~3次大作业博客

前言
java语言和c语言真的很不同!c是面向过程,它更加注重程序的执行过程,需要程序员手动管理内存等资源。java是面向对象,它更注重于对象的概念,提供了更高级的特性如继承、封装、多态等,同时也有自动内存管理机制(垃圾回收),使得程序员可以更专注于业务逻辑而不用过多关注底层细节。另外,题目难度和代码的复杂度来说,java也远远大于c,我们需要摆脱c语言的思维,去转变思维进行面向对象的编程,重点是如何设计对象以及对象之间的交互,而不再像C那样只关注函数和数据。这需要习惯于思考更高层次的抽象和模块化思维。

第一次作业

1.知识点:多个类的使用,类的初始化,其中一个类可以调用另一个类的方法或者访问其属性,创建对象进行使用类,多个类之间的调用可以通过在一个类中创建另一个类的对象来实现,然后通过这些对象之间的方法调用或属性访问来进行交互。数据的保存和输出,可以使用数组、集合(如ArrayList或LinkedList)等数据结构,如何将输入的数据拆分转化并且保存留用,通过字符串的分割(如使用split方法)和类型转换来实现。对字符的处理,比对,判断

2.题量适中,难度适中

7-1 设计一个风扇Fan类

import java.util.*;

 class Fan{
    int SLOW=1,MEDIUE=2,FAST=3;
   private int speed=1;
   private boolean on=false;
   private double radius=5;
   private String color="white";
    Fan()
    {}
    public Fan(int fanSpeed,boolean fanOn,double fanRadius,String fanColor)
    {
        this.speed=fanSpeed;
        this.on=fanOn;
        this.radius=fanRadius;
        this.color=fanColor;
    }
    public String toString()
    {
        String s;
        if(this.on==false) {
            s="speed "+speed+"\n";
		s=s+"color "+color+"\n";
		s=s+"radius "+radius+"\n";
			s=s+"fan is off";
		}else {
             s="speed "+speed+"\n";
		s=s+"color "+color+"\n";
		s=s+"radius "+radius+"\n";
			s=s+"fan is on";
		}
		
	    return s;
    }
    
}
public class Main{
    public static void main(String[] args) {
    Fan fan1=new Fan();
        Scanner input=new Scanner(System.in);
	int fanSpeed=input.nextInt() ;
	boolean fanOn=input.nextBoolean();
	double fanRadius=input.nextDouble();
	String fanColor=input.next();
	Fan fan2=new Fan(fanSpeed, fanOn,fanRadius,fanColor);
        System.out.println("-------\n"+ "Default\n"+ "-------");
        System.out.println(fan1.toString());
		System.out.println("-------\n"+ "My Fan\n"+ "-------");
        System.out.println(fan2.toString());
    }
}

7-2 类和对象的使用

import java.util.*;
class Student{
   private String name;
    private String sex;
    private String studentID;
    private int age;
    private String major;
    public Student()
    {}
    public Student(String name,String sex,String studentID,int age,String major)
    {
        this.name=name;
        this.sex=sex;
        this.studentID=studentID;
        this.age=age;
        this.major=major;
    }
   // public getter()
    //{
        
    //}
     public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getSex() {
        return sex;
    }
 
    public void setSex(String sex) {
        this.sex = sex;
    }
 
    public String getStudentID() {
        return studentID;
    }
 
    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getMajor() {
        return major;
    }
 
    public void setMajor(String major) {
        this.major = major;
    }

    public String toString()
    {
        return "姓名:" + name + ",性别:" + sex + ",学号:" + studentID + ",年龄:" + age + ",专业:" + major;
    }
  public void printInfo()
    {
        System.out.println(toString());
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String name = input.next();
        String sex = input.next();
        int age = input.nextInt();
        String major = input.next();
         String studentID = input.next();
        Student student=new Student(name,sex,studentID,age,major);
         student.printInfo();
      

    }

}

7-3 成绩计算-1-类、数组的基本运用

import java.util.Scanner;

class Student {
private String id;
private String name;
private int chinese;
private int math;
private int physics;

    Student ()
    {}
public Student(String id, String name, int chinese, int math, int physics) {
this.id = id;
this.name = name;
this.chinese = chinese;
this.math = math;
this.physics = physics;
}

public int sum() {
return chinese + math + physics;
}

public double Average() {
return sum() / 3.0;
}

public String getName() {
return name;
}

public String getId() {
return id;
}

public int getChinese() {
return chinese;
}

public int getPhysics() {
return physics;
}


public int getMath() {
return math;
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

Student[] students = new Student[5];
int i;
for (i = 0; i < 5; i++) {
String[] in = input.nextLine().split(" ");
    String id = in[0];
String name = in[1];

int chinese = Integer.parseInt(in[2]);
int math = Integer.parseInt(in[3]);
int physics = Integer.parseInt(in[4]);

students[i] = new Student(id, name, chinese, math, physics);
}

for (i = 0; i < 5; i++) {
int sum = students[i].sum();
double average= students[i].Average();
System.out.printf("%s %s %d %.2f\n",students[i].getId(), students[i].getName(), sum, average);
}

}
}

7-4 成绩计算-2-关联类

import java.util.Scanner;
 class Grade{
 private int day;
 private int finall;
 public  Grade(int day,int finall)
 {
    this.day=day;
     this.finall=finall;
 }
 
 public int test()
 {
     int test;
     test=(int)(day*0.4+finall*0.6);
     return test;
 }
 public int getday()
{
return day;
}
public int getfinall()
{
return finall;
}
}
class  Student {
private String id;
private String name;
private Grade chinese;
private Grade math;
private Grade physics;

 Student ()
 {}
public Student(String id, String name ) {
this.id = id;
this.name = name;
//this.chinese = chinese;
//this.math = math;
//this.physics = physics;
}


 public int getall()
{
return chinese.test()+math.test()+physics.test();
}
public double getavg()
{

double sum=chinese.test()+math.test()+physics.test();

return (double)(sum/3);
}
public double getavgday()
{
double sum=chinese.getday()+math.getday()+physics.getday();

return (double)(sum/3);
}
public double getavgfinall()
{
double sum=chinese.getfinall()+math.getfinall()+physics.getfinall();
return (double)(sum/3);
}



public String getName() {
return name;
}

public String getId() {
return id;
}
public Grade getchinese() {
return chinese;
}

public Grade getphysics() {
return physics;
}


public Grade getmath() {
return math;
}
public void setchinese(Grade chinese) {
this.chinese = chinese;

}

public void  setphysics(Grade physics) {

this.physics = physics;


}


public void  setmath(Grade math) {

this.math = math;

}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

Student[] students = new Student[3];
 Grade[] grades=new Grade[3];
int i,count=0;
for(i=0;i<9;i++)
{
String id= input.next();
String name = input.next();
String project = input.next();
int day =input.nextInt();
int finall =input.nextInt();
int j=i%3;

if(j==0)
{
students[count]=new Student(id,name);
students[count].setchinese(new Grade(day,finall));
}
if(j==1)
{
students[count].setmath(new Grade(day,finall));
}
if(j==2)
{
students[count].setphysics(new Grade(day,finall));
count++;
}
}

for (i = 0; i < 3; i++) {

System.out.printf("%s %s %d %.2f %.2f %.2f\n",students[i].getId(), students[i].getName(), students[i].getall()  , students[i].getavgday(),students[i].getavgfinall(),students[i].getavg());
}

}
}

7-5 答题判题程序-1

import java.util.*;
class Question{
   private int id;//编号
       private String in;//内容
    private String standardanswer;//标准答案
    public Question(int id, String in, String standardanswer) {
        this.id = id;
        this.in = in;
        this.standardanswer = standardanswer;
    }
    public void setid(int id)
    {
        this.id=id;
    }
     public void setin(String in)
    {
        this.in=in;
    }
     public void setstandardanswer(String standardanswer)
    {
        this.standardanswer=standardanswer;
    }
    public int getid()
    {
        return id;
    }
    public String getin()
    {
        return in;
    }
    public String getstandardanswer()
    {
        return standardanswer;
    }
    public boolean judje(String answer)
    {//判断
        //int flag=0;
        return(standardanswer.equals(answer));
           // flag=1;
       // return flag;
    }
    
}
class Paper
{
       private Question[] list;//题目列表
   private int num;//题目数量
    public Paper(int num) {
        this.num=num;
        this.list = new Question[num];
    }
    public Question getlist(int i)
    {
        return list[i];
    }
    public int getnum() {
        return num;
    }
   /* public boolean judje2(int id,String answer)
    {//判断
        
        return(list[id-1].judje(answer));
            
        //return flag;
    } */
public boolean judje2(int id, String answer)
{//判断
    if (list[id-1] != null) {
        return list[id-1].judje(answer);
    } else {
        // 处理题目为空的情况,这里简单地返回false
        return false;
    }
}
    
    public void save(int id,Question question)
    {//保存题目
        list[id-1]=question;
    }
}
class Anspaper//答卷
{
   private Paper papers;//试卷
    private String[] answer;//答案列表
    private boolean[] judje;//判题列表(t or f)
    public Anspaper(Paper papers) {
        this.papers = papers;
        this.answer = new String[papers.getnum()];
        this.judje = new boolean[papers.getnum()];
    }
    public void judje3()//判题
    {int i=0;
       for (i = 0; i < papers.getnum(); i++) {
            judje[i] = papers.judje2(i + 1, answer[i]);
        }
    }
    public void print()//输出
    {
        for (int i = 0; i < papers.getnum(); i++) {
            System.out.println( papers.getlist(i).getin()  +"~"+answer[i]
);
        }
        for (int i = 0; i < papers.getnum(); i++) {
            if(i<papers.getnum()-1)
           System.out.print((judje[i] ? "true" : "false")+" ");
            if(i==papers.getnum()-1)
           System.out.print((judje[i] ? "true" : "false"));
        }
    
    }
    
    public void saveans(int id ,String answers)
    {//保存答案
        if(id==1)
            answer[id-1]=answers;
        if(id>1)
         answer[id - 1] = answers.substring(3);
        //answer[id-1]=answers;
    }
    public String getanswer(int i)
    {
        return answer[i];
    }
}
public class Main{
    public static void main(String[] args){
        Scanner input=new Scanner(System.in);
        int num=input.nextInt();
        input.nextLine(); //
        Paper papers=new Paper(num);

  
        for(int i=0;i<num;i++)
        {  
            String[] strings = input.nextLine().split("#");
            int id = Integer.parseInt(strings[1].substring(2).trim());
            String in = strings[2].substring(2);
            String standardanswer =  strings[3].substring(2);
            papers.save(id, new Question(id,in.trim(), standardanswer.trim()));
        }
        Anspaper answerpaper=new Anspaper(papers);
        while (input.hasNextLine()) {
    String line = input.nextLine();
    if (line.equals("end"))
        break;
    String[] answer = line.substring(3).split(" ");
    for (int i = 0; i < answer.length; i++) {
        answerpaper.saveans(i + 1, answer[i]);
    }
}
        /*while(input.hasNextLine())
        {
            String line=input.nextLine();
            if(line.equals("end"))
                break;
        //String[] str=input.nextLine().split(" ");
       String[] answer=line.substring(3).split(" ");
        for (int i=0;i<answer.length;i++)
        {
            answerpaper.saveans(i+1,answer[i]);
        }

        }*/
        answerpaper.judje3();
        answerpaper.print();
        input.close();
    }
   
}

第二次作业

1.知识点:数据的排序,动态数组和链表的使用,类与对象的运用,对于乱序输入数据的处理,可以先将数据存储在数组或集合中,然后使用排序算法对其进行排序或者使用Map来进行存储。拆分可以使用字符串的split方法或者正则表达式来实现,将数据按照特定的规则进行分割。缺失数据的处理可以通过特定的标记或者占位符来表示缺失,并在程序中进行相应的处理。多行数据的处理可以使用循环结构逐行读取数据,并进行相应的处理。题目与分值的对应和统计可以使用Map或者其他数据结构来进行存储,循环多次进行判断输出等,map的运用,数据的遍历和使用

2.题量偏大,难度偏高

7-4 答题判题程序-2

import java.util.*;

   class Question {
   private int id; // 编号
   private String in; // 内容
   private String standardAnswer; // 标准答案

   public Question(int id, String in, String standardAnswer) {
       this.id = id;
       this.in = in;
       this.standardAnswer = standardAnswer;
   }

   public void setId(int id) {
       this.id = id;
   }

   public void setIn(String in) {
       this.in = in;
   }

   public void setStandardAnswer(String standardAnswer) {
       this.standardAnswer = standardAnswer;
   }

   public int getId() {
       return id;
   }

   public String getIn() {
       return in;
   }

   public String getStandardAnswer() {
       return standardAnswer;
   }

   public boolean judge(String answer) {
       return standardAnswer.equals(answer);
   }
}

class Paper {
   int paperid;//试卷编号
   private ArrayList<Question> list; // 题目列表
List<Score> Scores;
   public Paper() {
       this.list = new ArrayList<>();
   }
public Paper(int paperid) {
       this.paperid = paperid;
       this.Scores =new ArrayList<>();
   }//初始化和创建map
   public void addQuestion(Question question) {
       list.add(question);
   }

   public Question getQuestion(int i) {
       return list.get(i);
   }

   public int getNumQuestions() {
       return list.size();
   }
   public void addScore(Score score) {//将题目的序号和对应分数写入
       Scores.add(score);
   }
public List<Score> getScores() {
       return Scores;
   }
   public boolean judgeQuestion(int id, String answer) {
       if (id >= 1 && id <= list.size()) {
           return list.get(id - 1).judge(answer);
       } else {
           return false; // 题目编号超出范围返回false
       }
   }
}

class AnswerPaper {
   int ansid;//答卷编号
   private Paper paper; // 试卷
   // ArrayList<String> answers; // 答案列表
List<String> answers;//学生答案数组
   public AnswerPaper(int ansid) {
       this.ansid=ansid;
      // this.paper = paper;
       this.answers = new ArrayList<>();
   }
public AnswerPaper(Paper paper) {
       //this.ansid=ansid;
       this.paper = paper;
       this.answers = new ArrayList<>();
   }
   public void addAnswer(String answer) {
       answers.add(answer);
   }

   public void judgeAnswers() {
       for (int i = 0; i < paper.getNumQuestions(); i++) {
           
           
           String answer = i <answers.size()  ? answers.get(i) : "answer is null";
               if(answer=="answer is null")
               {  System.out.println("answer is null");
               }
               else
               {
                   boolean result = paper.judgeQuestion(i + 1, answers.get(i));
                  System.out.println(paper.getQuestion(i).getIn()+ "~" + answers.get(i) + "~" + result);
               }


           
           
       }
   }

   public void printScore() {
       int totalScore = 0;
       for (int i = 0; i < paper.getNumQuestions(); i++) {
           if (i < answers.size() && paper.judgeQuestion(i + 1, answers.get(i))) {
               totalScore += 10; // 正确答案得10分
           }
       }
       System.out.println(totalScore / 10 + " " + totalScore % 10 + " 0~" + totalScore); // 输出得分
   }
}
class Score{
   int num;//题号
   int score;//分数
   public Score(int num,int score) {//初始化
        this.num = num;
       this.score= score;
   }
   public int getNum()
   {  return num;
   }
    public int getScore()
   {  return score;
   }
}

public class Main {
   public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
Map<Integer, Paper> papers = new HashMap<>();//试卷编号——试卷
       Map<Integer, List<AnswerPaper>> answerpapers = new HashMap<>();//答卷编号——答卷
       Paper paper = new Paper();
List<Question> question1 = new ArrayList<>();//题目的数组
       while (input.hasNextLine()) {
           String line = input.nextLine().trim();
           if (line.equals("end"))
               break;
          else if (line.startsWith("#N:")) {
               String[] parts = line.split(" ");
              // String[] parts = line.split("#N:| #Q:| #A:");
               int id = Integer.parseInt(parts[0].substring(3));
               String in = parts[1].substring(3);
               String standardAnswer = parts[2].substring(3);
              
               question1.add(new Question(id, in, standardAnswer));
               paper.addQuestion(new Question(id, in, standardAnswer));
           }
       

       //AnswerPaper answerPaper = new AnswerPaper();

       
           //String line = input.nextLine().trim();
           if (line.equals("end"))
               break;
          if (line.startsWith("#S:")) {
               String[] parts = line.split(" ");
               int ansid = Integer.parseInt(parts[0].substring(3));
               AnswerPaper answerPaper = new AnswerPaper(ansid);
               for (int i = 1; i < parts.length; i++) {
                   answerPaper.addAnswer(parts[i].substring(3));
               }
if (answerpapers.containsKey(ansid))
                  {
                           answerpapers.get(ansid).add(answerPaper);
                  } else 
                  {
                          List<AnswerPaper> list = new ArrayList<>();
                          list.add(answerPaper);
                          answerpapers.put(ansid,list);
                  }
              
           }
       
          
              //String line = input.nextLine().trim();
          if (line.equals("end"))
               break;
       if (line.startsWith("#T:")) {
               String[] parts = line.split(" ");
               int paperid = Integer.parseInt(parts[0].substring(3));
               Paper paperr = new Paper(paperid);
               for (int i = 1; i < parts.length; i++) {
                   String[] questionScore = parts[i].split("-");
                   int questionNumber = Integer.parseInt(questionScore[0]);
                   int score = Integer.parseInt(questionScore[1]);
                 
                   Score nscore=new Score(questionNumber,score);
                   paperr.addScore(nscore);
               }
               papers.put(paperid, paperr);
        }}
AnswerPaper answerPaper = new AnswerPaper(paper);

//Answerpaper answerpaper = Answerpaper.get(j);
       

       for (int paperid : papers.keySet()) {
            Paper paper1 = papers.get(paperid);//创建遍历到的当前的试卷
           int total = 0;//总分
          
            for(Score score :paper1.getScores())
            {
               total =total+ score.getScore();//求试卷总分
           }
           if (total != 100) {
               System.out.printf("alert: full score of test paper%d is not 100 points\n",paperid);
           }//不是100则输出
          
           
         }
       
      for(int paperid : answerpapers.keySet())
          {
              if(!papers.containsKey(paperid))
              {  System.out.println("The test paper number does not exist");}
              else
              {
                    Paper paper2 = papers.get(paperid);//创建遍历到的当前的试卷
           List<Integer> tscore = new ArrayList<>();//存储当前的试卷各题的分数
            for(Score score :paper2.getScores())
            {
               tscore.add(score.getScore());
           }
         //在这里判断是否能不能找到对应的答卷编号
           
          List<AnswerPaper> Answerpapers = answerpapers.get(paperid);
         //循环输出多个相同编号的答卷
           for(int j = 0; j < Answerpapers.size();j++){
                AnswerPaper answerpaper = Answerpapers.get(j);
           List<Question> paperquestion = new ArrayList<>();//试卷里的题目
            for(Score score : paper2.getScores())
            {
                
               for(Question question : question1)
               {  
                   if(question.getId()==score.getNum())
                    { paperquestion.add(question);
                    }
               }
            }
           

           for (int i = 0; i < paperquestion.size();i++) {
               Question question = paperquestion.get(i);
               String answer = i < answerpaper.answers.size() ? answerpaper.answers.get(i) : "answer is null";
               if(answer=="answer is null")
               {  System.out.println("answer is null");
               }
               else
               {
                   boolean result = answer.equals(question.getStandardAnswer());
                  System.out.println(question.getIn() + "~" + answer + "~" + result);
               }
           }
          
           int totalScore = 0;
             int a=1;
              for (int i = 0; i < paperquestion.size();i++) {
               Question question = paperquestion.get(i);
               String answer = i < answerpaper.answers.size() ? answerpaper.answers.get(i) : "answer is null";
             
              if(answer.equals(question.getStandardAnswer()))
              {   totalScore=totalScore+tscore.get(i);
                 if(a==paperquestion.size())
                  System.out.print(tscore.get(i));
                     else
                   System.out.print(tscore.get(i)+" ");
              }
               else
              {   totalScore=totalScore+0;
               
                   if(a==paperquestion.size())
                  System.out.print("0");
                     else
                   System.out.print("0 ");
               
              }
                  a++;
           }
        
           System.out.printf("~%d\n",totalScore);

       }
              }
          }
   


      //answerPaper.judgeAnswers();
       //answerPaper.printScore();

       input.close();
   }
}
 

第三次大作业

1.知识点:封装性,它通过将数据和方法封装在类的内部,只对外部提供有限的接口来实现。日期类的使用日期类的方法,可以通过Java提供的Date类或者更加强大和灵活的LocalDate类来实现,它们提供了丰富的日期操作方法,如获取年份、月份、日期等,以及日期间的比较和计算等功能。类与类之间的联系,通过这些对象之间的方法调用或者属性访问来进行交互。调用,删除信息,乱序混合输入,根据需求进行排序或者其他处理。运用正则表达式可以对输入数据进行格式验证,以确保输入数据符合特定的格式要求,并进行错误情况的处理。错误引用的处理,错误格式,乱序交错输入的拆分保存调用输入数据 ,储存数据,输入为空的情况处理,可以在程序中进行判断并给出相应的提示。分情况处理

2.题量大,难度高

7-3 答题判题程序-3

import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher; 
class Question {
    private int number;//编号
     String content;//内容
     String answer;//答案

    public Question(int number, String content, String answer) {
        this.number = number;
        this.content = content;
        this.answer = answer;
    }

    public int getNumber() {
        return number;
    }

    public String getContent() {
        return content;
    }

    public String getAnswer() {
        return answer;
    }
    public boolean judge(String answers) {
        return answer.equals(answers);
}
}
class TestPaper {//试卷
    private int paperNumber;//SHIJVANBIANHAO
     private ArrayList<Question> list; // 题目列表
    private Map<Integer, Integer> questionScores;
    List<Score> Scores;//分数

    public TestPaper(int paperNumber) {
        this.paperNumber = paperNumber;
        questionScores = new HashMap<>();
        this.Scores =new ArrayList<>();
    }

    public void addQuestionScore(int questionNumber, int score) {
        questionScores.put(questionNumber, score);
    }
    public void addAumberScore(Score numberScore) {//将题目的序号和对应分数写入
        Scores.add(numberScore);
    }
    public List<Score> getScores() {
        return Scores;
    }
    

    public int getTotal() {
        int total = 0;
        for (int score : questionScores.values()) {
            total += score;
        }
        return total;
    }

    public boolean isFullScore() {
        return getTotal() == 100;
    }

    public int getPaperNumber() {
        return paperNumber;
    }

    public Map<Integer, Integer> getQuestionScores() {
        return questionScores;
    }
    public boolean judgeQuestion(int id, String answer) {
        if (id >= 1 && id <= list.size()) {
            return list.get(id - 1).judge(answer);
        } else {
            return false; // 题目编号超出范围返回false
        }
}
}

class Score//分数
{
    int number;//题号
    int score;//分数
    public Score(int number,int score) {//初始化
        this.number = number;
        this.score= score;
    }
    public int getNumber()
    {  return number;
    }
     public int getScore()
    {  return score;
    }
}
class Student {//学生及答案
    private String id;//学号
    private String name;//姓名
    int sheetNumber;//答卷编号
     Map<Integer, String> answers;//答案

    public Student(String id, int SheetNumber) {
        this.id = id;
        this.sheetNumber = sheetNumber;
        //this.name = name;
        answers = new HashMap<>();
    }

    public void addAnswer(int questionNumber, String answer) {
        answers.put(questionNumber, answer);
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Map<Integer, String> getAnswers() {
        return answers;
    }
}

public class Main {
    //private static List<Question> questions = new ArrayList<>();
    //private static List<TestPaper> testPapers = new ArrayList<>();
    //private static List<Student> students = new ArrayList<>();
    //private static List<String> deletedQuestions = new ArrayList<>();
static List<Question> questions = new ArrayList<>();//题目的数组
       static Map<Integer, TestPaper> testPapers = new HashMap<>();//试卷编号——试卷
       static Map<Integer, List<Student>> answerpaper = new HashMap<>();//答卷编号——答卷
      static  Map<String, String> students = new HashMap<>();//学号——姓名
       static List<Integer> deletes = new ArrayList<>();//删除的题目
    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
         //String line = scanner.nextLine().trim();
       // String line;
        //while (!(line = scanner.nextLine()).equals("end")) {
         while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
              if (line.equals("end")) {
                break;
            } else
            processInput(line);
           
        }


        for (int paperNumber : testPapers.keySet()) {
             TestPaper testPaper = testPapers.get(paperNumber);//创建遍历到的当前的试卷
            int total = 0;//总分
           
             for(Score numberScore :testPaper.getScores())
             {
                total =total+ numberScore.getScore();//求试卷总分
            }
            if (total != 100) {
                System.out.println("alert: full score of test paper" + paperNumber + " is not 100 points");
            }//不是100则输出
             
          }
        //第二次循环打印分数
           for(int paperNumber : answerpaper.keySet())
           {    //在这里判断是否能不能找到对应的答卷编号
               if(!testPapers.containsKey(paperNumber))
               {  System.out.println("The test paper number does not exist");}
               else
               {
                     TestPaper testPaper = testPapers.get(paperNumber);//创建遍历到的当前的试卷
            List<Integer> questionscore = new ArrayList<>();//存储当前的试卷各题的分数
             for(Score numberScore :testPaper.getScores())
             {
                questionscore.add(numberScore.getScore());
            }
        
            
           List<Student> Answerpapers = answerpaper.get(paperNumber);
          //循环输出多个相同编号的答卷
                   int i,j;
            for( i = 0; i < Answerpapers.size();i++){
                 Student answerSheet = Answerpapers.get(i);
           //存储本次检索试卷里的题目
            List<Question> paperquestion = new ArrayList<>();
                int a;
                a=200;
             for(Score numberScore :testPaper.getScores())
             {
                 Question targetQuestion = null; 
                for(Question question : questions)
                {   
                     if(question.getNumber()==numberScore.getNumber())
                     {    targetQuestion = question;
                         paperquestion.add(question);
                       break;
                     }
                }
                  if (targetQuestion == null) {
                      paperquestion.add(new Question(a,"delete","delete"));
                      a++;
                  }
             }
            
             
            for ( i = 0; i < paperquestion.size();i++) {////在这
               
                Question question = paperquestion.get(i);
         String answer = i < answerSheet.answers.size() ? answerSheet.answers.get(i+1) : "answer is null";
                if(answer=="answer is null")
                {  System.out.printf("answer is null\n");//
                }   
                    
                else 
                {   if(!deletes.contains(question.getNumber()))
                    {   if(question.getNumber()>=200)
                      {   System.out.println("non-existent question~0");
                      }
                      else
                      {boolean isCorrect = answer.equals(question.answer);
                      System.out.println(question.content + "~" + answer + "~" + isCorrect);
                      }
                    }
                    else
                    {  
                     System.out.println("the question "+question.getNumber()+" invalid~0");
                    }
                }
            }
          
        String studentname = students.get(answerSheet.getId());
        // 输出结果
        if (studentname != null) 
        {
             System.out.print(answerSheet.getId()+" "+studentname+": ");
              int totalScore = 0;
              int k=1;
               for (i = 0; i < paperquestion.size();i++) {
                Question question = paperquestion.get(i);
                String answer = i < answerSheet.answers.size() ? answerSheet.answers.get(i+1) : "answer is null";
              
               if(answer.equals(question.answer)&&!deletes.contains(question.getNumber()))
               {   if(question.getNumber()>=100) 
                  {
                   //totalScore=totalScore+0;
                
                    if(k==paperquestion.size())
                   System.out.print("0");
                      else
                    System.out.print("0 ");
                  }
                 else
                  {
                     totalScore=totalScore+questionscore.get(i);
                  if(k==paperquestion.size())
                   System.out.print(questionscore.get(i));
                      else
                    System.out.print(questionscore.get(i)+" ");
                  }
               }
                else
               {   
                
                    if(k==paperquestion.size())
                   System.out.print("0");
                      else
                    System.out.print("0 ");
                
               }
                   k++;
            }//
            System.out.printf("~%d\n",totalScore);
        } else 
        {
             System.out.print(answerSheet.getId()+" not found");
             continue;
        }
            

                }//相同卷号结束
            }//判断是否能查找到卷号结束
      }//for循环
        
           
                   
          
            
        
    
        //evaluateTestPapers();
        scanner.close();
    }

    private static void processInput(String line) {//判断输入
        if (line.startsWith("#N:")) {
            processQuestion(line);
        } else if (line.startsWith("#T:")) {
            processTestPaper(line);
        } else if (line.startsWith("#X:")) {
            processStudent(line);
        } else if (line.startsWith("#S:")) {
            processAnswer(line);
        } else if (line.startsWith("#D:")) {
            processDeletedQuestion(line);
        }
        else
            {
                System.out.println("wrong format:"+line);
            }
    }

    private static void processQuestion(String line) {//N
        String lines = "^#N:(.*) #Q:(.*) #A:(.*)$";
        Pattern pattern = Pattern.compile(lines);
        Matcher matcher = pattern.matcher(line);
                 if(matcher.matches())
             {
               String[] parts = line.split("#");
                String number = parts[1].substring(2);
                number=number.trim();
                String content = parts[2].substring(2);
                content=content.trim();
                String answer = parts[3].replace("A:", "");
               answer=answer.trim();
                Question  a=new Question(Integer.parseInt(number), content, answer);
                questions.add(a);
                }
                else
                {   System.out.println("wrong format:"+line);
                }
        
    }

    private static void processTestPaper(String line) {//T
Pattern patternTest = Pattern.compile("^#T:\\d+ \\d+-\\d+( \\d+-\\d+)*$");
               Matcher matcherTest=  patternTest.matcher(line);
               if(matcherTest.find())
                {
                String[] parts = line.split(" ");
                int paperNumber = Integer.parseInt(parts[0].substring(3));
                TestPaper testPaper = new TestPaper(paperNumber);
                for (int i = 1; i < parts.length; i++) {
                    String[] questionScorePair = parts[i].split("-");
                    int questionNumber = Integer.parseInt(questionScorePair[0]);
                    int score = Integer.parseInt(questionScorePair[1]);
                   // System.out.println(questionNumber+"  "+score);
                    Score numberScore=new Score(questionNumber,score);
                    testPaper.addAumberScore(numberScore);
                }
                testPapers.put(paperNumber, testPaper);
                }
               else
               {    System.out.println("wrong format:"+line);
               }
        
       
    }

    private static void processStudent(String line) {//X
 String ab=line.substring(3);
                  String[] parts = ab.split("-");
                  for (int i = 0; i < parts.length; i++) {
                       String[] IDname = parts[i].split(" ");
                        students.put(IDname[0], IDname[1]); 
        
        //String ab=line.substring(3);
                  //String[] parts = ab.split("-");
      
        }
    }

    private static void processAnswer(String line) {//S
String line1 = line.replace("#A:", "");
        
                String[] parts = line.split("#");
       // String part = parts[1].substring(2);
                 String[] part =  parts[1].substring(2).split(" ");
                int sheetNumber = Integer.parseInt(part[0]);
                String studentID = part[1];
                Student answerSheet=new Student(studentID,sheetNumber);
                for (int i = 2; i < parts.length; i++) {
                    String a = parts[i].substring(2).trim();
                    if(a!=null)
                    { String[] orderanswer = a.split("-");
                    int ordernumber = Integer.parseInt(orderanswer[0]);
                     String answer;
                      answer = orderanswer.length > 1 ? orderanswer[1] : "";
                     //if(orderanswer!=null)
                    // answer = orderanswer[1];
                     //if(orderanswer==null)
                      //   answer = " ";
                     //answer = orderanswer.length > 1 ? orderanswer[1] : "";
                    //System.out.println(ordernumber+" "+answer);
                     if(answer!= null)
                    answerSheet.addAnswer(ordernumber,answer);
                     else
                    {   String result = answer.replace("","yes");
                        answer=" ";
                        System.out.println(answer+"  b");
                        answerSheet.addAnswer(ordernumber,answer);
                   }
                    }
                }
                 
                   if (answerpaper.containsKey(sheetNumber))
                   {
                            answerpaper.get(sheetNumber).add(answerSheet);
                   } else 
                   {
                           List<Student> list = new ArrayList<>();
                           list.add(answerSheet);
                           answerpaper.put(sheetNumber,list);
        
      
    }
    }

private  static void processDeletedQuestion(String line) {//D
        
         //String line1=line.substring(3);
                 // String[] parts = line1.split(" ");
String line1=line.substring(3);
                  String[] parts = line1.split(" ");
                 for (int i = 0; i < parts.length; i++) {
                        String[] number = parts[i].split("-");
                         deletes.add(Integer.parseInt(number[1]));
                 }
        
        
    
   
    }
    
    private static void evaluateTestPapers() {
       
    }

    private static String findCorrectAnswer(int questionNumber) {
        for (Question question : questions) {
            if (question.getNumber() == questionNumber) {
                return question.getAnswer();
            }
        }
        return null;
    }

    private static Student findStudentById(String id) {
        /*for (Student student : students) {
            if (student.getId().equals(id)) {
                return student;
            }
        }*/
        return null;
    }
}

设计与分析

第一次大作业

主要是类与类之间的调用,相互联系和对字符的处理。不过一开始对类还并不熟悉,不能熟练运用。

第二次大作业

没有了题目个数,这就要用到动态数组及其相关函数。还新增了试卷,新增试卷类,建立试卷、题目、答卷之间的联系。还要把题目对应的分数一一对应计算

第三次大作业

主要是对错误情况的处理,多用正则表达式限制输入格式,要考虑多种情况,对输入的要求较高,注意细节,特别是内容为空的情况。新增了学生类,注意类之间的对应匹配。

踩坑心得

1.非零返回!!!!!真的害惨我了,每次都有非零返回,不同于编译错误,非零返回并不好找哪里出错了,也不好修改。但是大概率是输入的错误,所以要仔细检查输入的地方有没有可能输入为空,或者没进行输入就直接用了对应的变量,也就是变量还未初始化未赋值。

点击查看代码
> Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
> 	at Main.processStudent(Main.java:148)
> 	at Main.processInput(Main.java:111)
> 	at Main.main(Main.java:99)
2.静态static
> Main.java:142: error: non-static variable testPapers cannot be referenced from a static context
>         for (int paperNumber : testPapers.keySet()) {
>                                ^
> Main.java:143: error: non-static variable testPapers cannot be referenced from a static context
>              TestPaper testPaper = testPapers.get(paperNumber);//创建遍历到的当前的试卷
>                                    ^
> Main.java:156: error: non-static variable answerSheets cannot be referenced from a static context
>            for(int paperNumber : answerSheets.keySet())
>                                  ^
> Main.java:158: error: non-static variable testPapers cannot be referenced from a static context
>                if(!testPapers.containsKey(paperNumber))
>                    ^
> Main.java:162: error: non-static variable testPapers cannot be referenced from a static context
>                      TestPaper testPaper = testPapers.get(paperNumber);//创建遍历到的当前的试卷
>                                            ^
> Main.java:170: error: non-static variable answerSheets cannot be referenced from a static context
>            List<Student> AnswerSheets = answerSheets.get(paperNumber);
>                                         ^
> Main.java:180: error: non-static variable questions cannot be referenced from a static context
>                 for(Question question : questions)
>                                         ^
> Main.java:208: error: non-static variable deletes cannot be referenced from a static context
>                 {   if(!deletes.contains(question.getNumber()))
>                         ^
> Main.java:227: error: non-static variable students cannot be referenced from a static context
>         String studentname = students.get(answerSheet.getId());
>                              ^
> Main.java:238: error: non-static variable deletes cannot be referenced from a static context
>                if(answer.equals(question.answer)&&!deletes.contains(question.getNumber()))
>                                                    ^
> Main.java:322: error: non-static variable questions cannot be referenced from a static context
>                 questions.add(a);
>                 ^
> Main.java:346: error: non-static variable testPapers cannot be referenced from a static context
>                 testPapers.put(paperNumber, testPaper);
>                 ^
> Main.java:360: error: non-static variable students cannot be referenced from a static context
>                         students.put(IDname[0], IDname[1]); 
>                         ^
> Main.java:373: error: incompatible types: int cannot be converted to String
>                 Student answerSheet=new Student(sheetNumber,studentID);
>                                                 ^
> Main.java:385: error: non-static variable answerSheets cannot be referenced from a static context
>                    if (answerSheets.containsKey(sheetNumber))
>                        ^
> Main.java:387: error: non-static variable answerSheets cannot be referenced from a static context
>                             answerSheets.get(sheetNumber).add(answerSheet);
>                             ^
> Main.java:392: error: non-static variable answerSheets cannot be referenced from a static context
>                            answerSheets.put(sheetNumber,list);
>                            ^
> Main.java:406: error: non-static variable deletes cannot be referenced from a static context
>                          deletes.add(Integer.parseInt(number[1]));
>                          ^
> Main.java:415: error: non-static variable students cannot be referenced from a static context
>         for (Student student : students) {
>                                ^
> Main.java:416: error: non-static variable testPapers cannot be referenced from a static context
>             for (TestPaper testPaper : testPapers) {
>                                        ^
> Main.java:433: error: cannot find symbol
>                     if (deletedQuestions.contains("the question " + questionNumber + " invalid~0")) {
>                         ^
>   symbol:   variable deletedQuestions
>   location: class Main
> Main.java:454: error: non-static variable questions cannot be referenced from a static context
>         for (Question question : questions) {
>                                  ^
> Main.java:463: error: non-static variable students cannot be referenced from a static context
>         for (Student student : students) {
>                                ^
> Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output

3.类中的私有变量,是不能直接调用的,由于封闭性,需要调用相应的get函数
4.注释!!!很多时候没加注释真的忘了自己写的是什么,这样非常不利于后续的改进

改进建议:在编码中确实有很多地方可以改进,让我分享一些建议:

  1. 清晰的变量命名: 在编写代码时,使用清晰、具有象征性的变量名是非常重要的。这有助于他人理解代码,也方便自己在回顾代码时理解。例如,ans 可能不够清晰,可以考虑更具描述性的名称>answer

  2. 代码重构: 定期进行代码重构是一个好习惯,可以通过将重复的代码提取为方法或者函数,提高代码的复用性和可维护性。此外,也可以根据需要进行代码结构的优化,使其更加简洁和清晰。

通过不断地改进和优化,可以使代码更加可读、可维护、可测试和可扩展,从而实现可持续的开发和改进。

总结

对本阶段的三次题目集进行综合性总结,我学到了很多关于编程和软件开发的重要知识和技能。以下是我的总结:

  1. 学习收获: 通过完成三次题目集,我深入了解了面向对象编程语言(java)的基础知识,包括字符和字符串操作、类与对象、算法等方面。我学会了如何解决问题、优化代码以及进行代码调试。这些都是我在软件开发中必不可少的技能。

  2. 进一步学习和研究: 尽管我在本阶段取得了一些进步,但我也意识到自己还有很多需要进一步学习和研究的地方。例如,我希望能够深入学习算法和数据结构,以提高自己的编程能力和解决问题的能力。此外,我还希望学习更多关于软件工程和系统设计方面的知识,以便能够更好地设计和开发复杂的软件系统。

  3. 改进建议:

    • 教师: 希望教师能够提供更多的指导和支持。

    • 作业: 建议作业设计能够更加渐变灵活,既能够巩固基础知识,又能够提高解决问题的能力。

    • 实验: 希望实验内容能够更加贴近课程内容,能够帮助学生将理论知识应用到实际项目中。

    • 课上及课下组织方式: 建议课堂教学能够更加互动和灵活,充分调动学生的学习积极性和主动性。

在未来,我希望能够进一步学习算法和数据结构,提高自己的编程水平。
总的来说,我认为本阶段的学习给我带来了很多启发和提高,我会继续努力学习,提高自己的专业水平。