前三次大作業部落格總結

自云间發表於2024-04-21

第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. 改進建議:

    • 教師: 希望教師能夠提供更多的指導和支援。

    • 作業: 建議作業設計能夠更加漸變靈活,既能夠鞏固基礎知識,又能夠提高解決問題的能力。

    • 實驗: 希望實驗內容能夠更加貼近課程內容,能夠幫助學生將理論知識應用到實際專案中。

    • 課上及課下組織方式: 建議課堂教學能夠更加互動和靈活,充分調動學生的學習積極性和主動性。

在未來,我希望能夠進一步學習演算法和資料結構,提高自己的程式設計水平。
總的來說,我認為本階段的學習給我帶來了很多啟發和提高,我會繼續努力學習,提高自己的專業水平。

相關文章