OOP課程·PTA題目集1-3總結

nchuqiuj發表於2024-04-20

一. 前言

  1. 第一次pta比較簡單,主要考察了類的關聯與依賴,只有一道大題與4個小題
  2. 第二次pta比較難,主要考察了類設計,有一道大題與3個小題
  3. 第三次pta較難,主要考察了類設計,日期類的基本使用,有2個小題與1個大題

二.設計與分析
第一次題目集

  • 7-1 設計一個風扇Fan類
    原始碼:
點選檢視程式碼
import java.util.Scanner;
class Fan{
    private final int SLOW = 1;
    private final int MEDIUM = 2;
    private final int FAST = 3;
    private int speed;
    private boolean on;
    private double radius;
    private String color;
    public Fan(){
        this.speed = SLOW;
        this.on = false;
        this.radius = 5;
        this.color = "white";
    }
    public Fan(int speed, boolean on, double radius, String color) {
        this.speed = speed;
        this.on = on;
        this.radius = radius;
        this.color = color;
    }
    public int getSpeed() {
        return this.speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    public boolean isOn() {
        return this.on;
    }

    public void setOn(boolean on) {
        this.on = on;
    }

    public double getRadius() {
        return this.radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    public String color() {
        return this.color;
    }

    public void setColor(String color) {
        this.color = color;
    }
    public String toString() {
        if (on) {
            return "speed " + this.speed +"\n"+ "color " + this.color +"\n"+ "radius " + this.radius+"\n"+"fan is on\n";
        }
        else {
            return "speed " + this.speed +"\n"+ "color " + this.color +"\n"+ "radius " + this.radius+"\n"+"fan is off\n";
        }
    }
}
public class Main{
    public static void main(String[]args){
        Scanner input=new Scanner(System.in);
        Fan fan1=new Fan();
        Fan fan2=new Fan(input.nextInt(),input.nextBoolean(),input.nextDouble(),input.next());
        System.out.printf("-------\nDefault\n-------\n");
        System.out.print(fan1.toString());
        System.out.printf("-------\nMy Fan\n-------\n");
        System.out.print(fan2.toString());
    }

類圖:

分析:按照題意設計風扇類,對輸入輸出進行處理即可

  • 7-2 類和物件的使用
    原始碼:
點選檢視程式碼
import java.util.Scanner;
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,int age,String major,String studentID){
        this.name=name;
        this.sex=sex;
        this.studentID=studentID;
        this.age=age;
        this.major=major;
    }
   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 "姓名:"+this.name+",性別:"+this.sex+",學號:" + this.studentID+",年齡:"+this.age+",專業:"+this.major;
    }
    public void printlnfo(){
        System.out.printf("%s",toString());
    }
}
public class Main{
    public static void main(String[]args){
        Scanner input=new Scanner(System.in);
        Student student=new Student(input.next(),input.next(),input.nextInt(),input.next(),input.next());
        student.printlnfo();
    }
}

類圖:

分析:按題意設計學生類,建立學生物件並初始化,再輸出學生資訊

  • 7-3 成績計算-1-類、陣列的基本運用
    原始碼:
點選檢視程式碼
import java.util.Scanner;
import java.text.DecimalFormat;
import java.math.BigDecimal;
class Student{
    private String studentID;
    private String name;
    private int chineseGrade;
    private int mathGrade;
    private int physicsGrade;
    public Student(){
        
    }
    public Student(String studentID,String name,int chineseGrade,int mathGrade,int physicsGrade){
        this.studentID=studentID;
        this.name=name;
        this.chineseGrade=chineseGrade;
        this.mathGrade=mathGrade;
        this.physicsGrade=physicsGrade;
    }
    public int sum(){
        return this.chineseGrade+this.mathGrade+this.physicsGrade;
    }
    public double average(){
        double f=(double)this.sum()/3.00;
        return f;
    }
    public String toString(){
        double f=this.average();
        DecimalFormat df = new DecimalFormat("#.00");
        return this.studentID+" "+this.name+" "+this.sum()+" "+df.format(f)+"\n";
    }
}
public class Main{
    public static void main(String[]args){
        Scanner input =new Scanner(System.in);
        Student student1=new Student(input.next(),input.next(),input.nextInt(),input.nextInt(),input.nextInt());
        Student student2=new Student(input.next(),input.next(),input.nextInt(),input.nextInt(),input.nextInt());
        Student student3=new Student(input.next(),input.next(),input.nextInt(),input.nextInt(),input.nextInt());
        Student student4=new Student(input.next(),input.next(),input.nextInt(),input.nextInt(),input.nextInt());
        Student student5=new Student(input.next(),input.next(),input.nextInt(),input.nextInt(),input.nextInt());
        System.out.print(student1.toString());
        System.out.print(student2.toString());
        System.out.print(student3.toString());
        System.out.print(student4.toString());
        System.out.print(student5.toString());
    }
}

類圖:

分析:按照題意設計學生類,初始化物件並輸出成績。

  • 7-4成績計算-2-關聯類
    原始碼:
點選檢視程式碼
import java.util.Scanner;
import java.text.DecimalFormat;
import java.math.BigDecimal;
class Grade{
    private int usualGrade;
    private int finalGrade;
    public Grade(){
    }
    public Grade(int usualGrade,int finalGrade){
        this.usualGrade=usualGrade;
        this.finalGrade=finalGrade;
    }
    public int totalGrade(){
        return (int)(this.usualGrade*0.4+this.finalGrade*0.6);
    } 
    public int getUsualGrade(){
        return this.usualGrade;
    }
    public int getFinalGrade(){
        return this.finalGrade;
    }
}
class Student{
    private String studentID;
    private String name;
    private Grade chineseGrade;
    private Grade mathGrade;
    private Grade physicsGrade;
    public Student(){
        
    }
    public Student(String studentID,String name,Grade chineseGrade,Grade mathGrade,Grade physicsGrade){
        this.studentID=studentID;
        this.name=name;
        this.chineseGrade=chineseGrade;
        this.mathGrade=mathGrade;
        this.physicsGrade=physicsGrade;
    }
    public int sumTotal(){
        return this.chineseGrade.totalGrade()+this.mathGrade.totalGrade()+this.physicsGrade.totalGrade();
    }
    public int sumUsual(){
        return this.chineseGrade.getUsualGrade()+this.mathGrade.getUsualGrade()+this.physicsGrade.getUsualGrade();
    }
    public int sumFinal(){
        return this.chineseGrade.getFinalGrade()+this.mathGrade.getFinalGrade()+this.physicsGrade.getFinalGrade();
    }
    public double averageTotal(){
        double f=(double)this.sumTotal()/3.00;
        return f;
    }
    public double averageUsual(){
        double f=(double)this.sumUsual()/3.00;
        return f;
    }
    public double averageFinal(){
        double f=(double)this.sumFinal()/3.00;
        return f;
    }
    public String toString(){
        double f1=this.averageTotal();
        double f2=this.averageUsual();
        double f3=this.averageFinal();
        DecimalFormat df = new DecimalFormat("#.00");
        
        return this.studentID+" "+this.name+" "+this.sumTotal()+" "+df.format(f2)+" "+df.format(f3)+" "+df.format(f1)+"\n";
    }
}
public class Main{
    public static void main(String[]args){
        Scanner input=new Scanner(System.in);
        Student []stu=new Student[3];
        for(int i=0;i<3;i++){
            Grade chineseGrade=new Grade();
            Grade mathGrade=new Grade();
            Grade physicsGrade=new Grade();
            String studentID11=input.next();
            String name11=input.next();
            String subject1=input.next();
            switch(subject1){
                case "語文":chineseGrade=new Grade(input.nextInt(),input.nextInt());break;
                case "數學":mathGrade=new Grade(input.nextInt(),input.nextInt());break;
                case "物理":physicsGrade=new Grade(input.nextInt(),input.nextInt());break;
            }
            String studentID12=input.next();
            String name12=input.next();
            String subject2=input.next();
            switch(subject2){
                case "語文":chineseGrade=new Grade(input.nextInt(),input.nextInt());break;
                case "數學":mathGrade=new Grade(input.nextInt(),input.nextInt());break;
                case "物理":physicsGrade=new Grade(input.nextInt(),input.nextInt());break;
            }
            String studentID13=input.next();
            String name13=input.next();
            String subject3=input.next();
            switch(subject3){
                case "語文":chineseGrade=new Grade(input.nextInt(),input.nextInt());break;
                case "數學":mathGrade=new Grade(input.nextInt(),input.nextInt());break;
                case "物理":physicsGrade=new Grade(input.nextInt(),input.nextInt());break;
            }
            stu[i]=new Student(studentID11,name11,chineseGrade,mathGrade,physicsGrade);
            System.out.print(stu[i].toString());
        }
    }
}

類圖:

分析:運用了類的關聯,把成績類作為學生類的屬性,處理輸入,再輸出

  • 7-5答題判題程式-1
    設計實現答題程式,模擬一個小型的測試,要求輸入題目資訊和答題資訊,根據輸入題目資訊中的標準答案判斷答題的結果。
    輸入格式:
    程式輸入資訊分三部分:

1、題目數量
格式:整數數值,若超過1位最高位不能為0,
樣例:34

2、題目內容
一行為一道題,可以輸入多行資料。
格式:"#N:"+題號+" "+"#Q:"+題目內容+" "#A:"+標準答案
格式約束:題目的輸入順序與題號不相關,不一定按題號順序從小到大輸入。
樣例:#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
3、答題資訊
答題資訊按行輸入,每一行為一組答案,每組答案包含第2部分所有題目的解題答案,答案的順序號與題目題號相對應。
格式:"#A:"+答案內容
格式約束:答案數量與第2部分題目的數量相同,答案之間以英文空格分隔。
樣例:#A:2 #A:78
2是題號為1的題目的答案
78是題號為2的題目的答案
答題資訊以一行"end"標記結束,"end"之後的資訊忽略。
輸出格式:
1、題目數量
格式:整數數值,若超過1位最高位不能為0,
樣例:34
2、答題資訊
一行為一道題的答題資訊,根據題目的數量輸出多行資料。
格式:題目內容+" ~"+答案
樣例:1+1=~2
2+2= ~4
3、判題資訊
判題資訊為一行資料,一條答題記錄每個答案的判斷結果,答案的先後順序與題目題號相對應。
格式:判題結果+" "+判題結果
格式約束:
1、判題結果輸出只能是true或者false,
2、判題資訊的順序與輸入答題資訊中的順序相同
樣例:true false true
輸入樣例1:
單個題目。例如:

1
#N:1 #Q:1+1= #A:2
#A:2
end

輸出樣例1:
在這裡給出相應的輸出。例如:

1+1=~2
true

輸入樣例2:
單個題目。例如:

1
#N:1 #Q:1+1= #A:2
#A:4
end

輸出樣例2:
在這裡給出相應的輸出。例如:

1+1=~4
false

輸入樣例3:
多個題目。例如:

2
#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
#A:2 #A:4
end

輸出樣例3:
在這裡給出相應的輸出。例如:

1+1=~2
2+2=~4
true true

輸入樣例4:
多個題目。例如:

2
#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
#A:2 #A:2
end

輸出樣例4:
在這裡給出相應的輸出。例如:

1+1=~2
2+2=~2
true false

輸入樣例5:
多個題目,題號順序與輸入順序不同。例如:

2
#N:2 #Q:1+1= #A:2
#N:1 #Q:5+5= #A:10
#A:10 #A:2
end

輸出樣例5:
在這裡給出相應的輸出。例如:

5+5=~10
1+1=~2
true true

輸入樣例6:
含多餘的空格符。例如:

1
#N:1 #Q: The starting point of the Long March is #A:ruijin
#A:ruijin
end

輸出樣例6:
在這裡給出相應的輸出。例如:

The starting point of the Long March is~ruijin
true

輸入樣例7:
含多餘的空格符。例如:

1
#N: 1 #Q: 5 +5= #A:10
#A:10
end

輸出樣例7:
在這裡給出相應的輸出。例如:

5 +5=~10
true

設計建議:
以下是針對以上題目要求的設計建議,其中的屬性、方法為最小集,實現程式碼中可根據情況新增所需的內容:

題目類(用於封裝單個題目的資訊):

屬性:題目編號、題目內容、標準答案-standardAnswer
方法:資料讀寫set\get方法、
     判題方法(答案-answer):判斷答案-answer是否符合標準答案-standardAnswer

試卷類(用於封裝整套題目的資訊)

屬性:題目列表(題目類的物件集合)、題目數量
方法:判題方法(題號-num、答案-answer):判斷答案-answer是否符合對應題號的題目標準答案-standardAnswer
     儲存題目(題號-num、題目-question):將題目儲存到題目列表中,儲存位置與num要能對應

答卷類(用於封裝答題資訊)

屬性:試卷(試卷類的物件)、答案列表(儲存每一題的答案)、判題列表(儲存每一題的判題結果true/false)
方法:判題方法(題號-num):判斷答案列表中第num題的結果是否符合試卷中對應題號的題目標準答案
     輸出方法(題號-num):按照題目的格式要求,輸出題號為num的題目的內容和答題結果。
     儲存一個答案(題號-num,答案-answer):儲存題號為num的題目的答題結果answer。

原始碼:

點選檢視程式碼
import java.util.*;
import java.lang.*;
class Question{
    private int number;
    private String content;
    private String standardAnswer;
    public Question(int number, String content, String standardAnswer) {
        this.number = number;
        this.content = content;
        this.standardAnswer = standardAnswer;
    }
    public void setNumber(int number){
        this.number=number;
    }
    public void setContent(String content) {
       this.content = content;
    }
    public void setStandardAnswer(String standardAnswer) {
        this.standardAnswer = standardAnswer;
    }
    public int getNumber() {
        return number;
    }
    public String getContent() {
        return content;
    }
    public String getStandardAnswer() {
        return standardAnswer;
    }
    
    public boolean checkAnswer(String answer) {
        return answer.equals(standardAnswer);
    }
}

class ExaminationPaper{
    private List<Question>questionList;
    private int questionCount;
    public ExaminationPaper(int questionCount) {
        this.questionList = new ArrayList<>(questionCount);
        this.questionCount = questionCount;
    }
    public void addQuestion(int n,Question question) {
        questionList.add(n,question);
    }
    public boolean checkAnswer(int num,String answer){
        Question question = questionList.get(num);
        return question.checkAnswer(answer);
    }
    public Question question(int num){
        return questionList.get(num);
    }
}

class Answer{
    private ExaminationPaper test;
    private List<String>answers;
    private List<Boolean>results;
    public Answer(ExaminationPaper test,int questionCount){
        this.test=test;
        answers = new ArrayList<>(questionCount);
        results = new ArrayList<>(questionCount);
    }
    public void addAnswer(int n,String answer){
        answers.add(n,answer);
    }
    public void addResults(int n){
        results.add(n,this.test.checkAnswer(n,answers.get(n)));
    }
    
    public void printResult(int n){
        for(int i=0;i<n;i++){
            String p=((this.test.question(i)).getContent()).substring(3);
            String q=p.trim();
            System.out.println(q+"~"+(answers.get(i)).substring(3));
        }
        for(int i=0;i<n;i++){
            System.out.print(results.get(i));
            if(i!=n-1)
                System.out.print(" ");
        }
    }
}
public class Main{
    public static void main(String [] args){
        Scanner input =new Scanner(System.in);
        int n=input.nextInt();
        input.nextLine();
        Question []question=new Question[n];
        ExaminationPaper test=new ExaminationPaper(100);       
        for(int i=0;i<n;i++){
            String line = input.nextLine();
            String line2=line.trim();
            String[] parts = line2.split("\\s+");
            String []parts2=new String[3];
            if(parts.length>3){
                int index1=0;
                int index2=0;
                int index3=0;
                for(int i1=0;i1<parts.length;i1++) {
                    if(parts[i1].contains("#N")){
                        index1=i1;
                    }
                    if(parts[i1].contains("#Q")){
                        index2=i1;
                    }
                    if(parts[i1].contains("#A")){
                        index3=i1;
                    }
                }
                parts2[0]=parts[index1];
                parts2[1]=parts[index2].trim();
                parts2[2]=parts[index3];
                for(int j=index1+1;j<index2;j++){
                    parts2[0]+=parts[j];
                }
                for(int j=index2+1;j<index3;j++){
                    parts2[1]+=" "+parts[j];
                }
                for(int j=index3+1;j<parts.length;j++){
                    parts2[2]+=parts[j];
                }
            }
            else{
                parts2[0]=parts[0];
                parts2[1]=parts[1];
                parts2[2]=parts[2];
            }
            int number = Integer.parseInt(parts2[0].substring(3));
            question[number-1]=new Question(number,parts2[1],parts2[2]);
        }
        for(int i=0;i<n;i++){
            test.addQuestion(i,question[i]);
        }
        Answer answers=new Answer(test,n);
        for(int i=0;i<n;i++){
            String ans=input.next();
            answers.addAnswer(i,ans);
        }
        for(int i=0;i<n;i++){
            answers.addResults(i);
        }
        answers.printResult(n);
    }
}

類圖:

分析:設計3個類,問題類,試卷類,答卷類。先對輸入字串進行處理拆分,儲存到問題中,把題目加到試卷中,把試卷加到答卷中,然後對答案字串拆分,儲存到答卷中,最後進行判題並輸出。

第二次題目集

  • 7-1 手機按價格排序、查詢
    原始碼:
點選檢視程式碼
import java.util.*;
class MobilePhone implements Comparable<MobilePhone> {
    private String type;
    private int price;
    public MobilePhone(){
    }
    public MobilePhone(String type,int price){
        this.type=type;
        this.price=price;
    }
    public int getPrice(){
        return this.price;
    }
    public String getType(){
        return this.type;
    }
    public String toString(){
        return "型號:"+this.type+",價格:"+this.price;
    }
    @Override
    public int compareTo(MobilePhone otherMobilePhone) {
        return this.price - otherMobilePhone.price;
    }
}
public class Main{
    public static void main(String[]args){
        Scanner input =new Scanner(System.in);
        LinkedList<MobilePhone> MobilePhoneList = new LinkedList<>();
        MobilePhoneList.add(new MobilePhone(input.next(),input.nextInt()));
        MobilePhoneList.add(new MobilePhone(input.next(),input.nextInt()));
        MobilePhoneList.add(new MobilePhone(input.next(),input.nextInt()));
        
        System.out.println("排序前,連結串列中的資料:");
        for(int i=0;i<3;i++){
            System.out.printf("%s\n",(MobilePhoneList.get(i)).toString());
        }
        Collections.sort(MobilePhoneList);
        
        System.out.println("排序後,連結串列中的資料:");
        for(int i=0;i<3;i++){
            System.out.printf("%s\n",(MobilePhoneList.get(i)).toString());
        }
        
        MobilePhone goal=new MobilePhone(input.next(),input.nextInt());
        int flag=0;
        for(int i=0;i<3;i++){
            if(goal.getPrice()==(MobilePhoneList.get(i)).getPrice()){
                System.out.println(goal.getType()+"與連結串列中的"+(MobilePhoneList.get(i)).getType()+"價格相同");
                flag=1;
                //break;
            }
        }
        if(flag==0){
            System.out.print("連結串列中的物件,沒有一個與"+goal.getType()+"價格相同的");
        }
    }
}

類圖:

分析:設計手機類,瞭解相關知識可實現Comparable介面,重寫compareTo方法,完成排序

  • 7-2sdut-oop-4-求圓的面積(類與物件)

原始碼:

點選檢視程式碼
import java.util.*;
class Circle{
    private int radius;
    public Circle(){
        this.radius=2;
        System.out.println("This is a constructor with no para.");
    }
    public Circle(int radius){
        if(radius>0)
            this.radius=radius;
        else
            this.radius=2;
        System.out.println("This is a constructor with para.");
    }
    public void setRadius(int radius){
        if(radius>0)
            this.radius=radius;
        else
            this.radius=2;
    }
    public int getRadius(){
        return this.radius;
    }
    public double getArea(){
        return this.radius*this.radius*Math.PI;
    }
    public String toString( ){
        return "Circle [radius=" + this.radius + "]";
    }
}
public class Main{
    public static void main(String[]args){
        Scanner input =new Scanner(System.in);
	    Circle c1=new Circle();
        System.out.printf("%s\n",c1.toString());
        System.out.printf("%.2f\n",c1.getArea());
        
        Circle c2=new Circle();
        System.out.printf("%s\n",c2.toString());
        System.out.printf("%.2f\n",c2.getArea());
        
        c1.setRadius(input.nextInt());
        System.out.printf("%s\n",c1.toString());
        System.out.printf("%.2f\n",c1.getArea());
        
        c2=new Circle(input.nextInt());
        System.out.printf("%s\n",c2.toString());
        System.out.printf("%.2f\n",c2.getArea());
        
    }
}

類圖:

分析:該題很簡單,瞭解類和物件的相關知識就能做出了

  • 7-3 Java類與物件-汽車類
    原始碼:
點選檢視程式碼
import java.util.*;

/**
 * @author Teacher
 *         主類,用來在pta中執行。
 *         其中有一處程式碼需要完善
 */
public class Main {
  public static void main(String[] args) {

    // 此處填寫合適的程式碼【1】
    // 生成汽車例項
    float a=0;
    Car car=new Car("bob",a,a);
      
    System.out.printf("車主:%s,速度:%.1f,角度:%.1f\n", car.getOwnerName(), car.getCurSpeed(), car.getCurDirInDegree());

    // 設定新速度
    car.changeSpeed(10);
    System.out.printf("車主:%s,速度:%.1f,角度:%.1f\n", car.getOwnerName(), car.getCurSpeed(), car.getCurDirInDegree());

    // 停車
    car.stop();
    System.out.printf("車主:%s,速度:%.1f,角度:%.1f\n", car.getOwnerName(), car.getCurSpeed(), car.getCurDirInDegree());

  }
}

/**
 * @author Teacher
 *         汽車類,其中有兩個內容需要完善。
 */
class Car {
  // 車主姓名
  private String ownerName;
  // 當前車速
  private float curSpeed;
  // 當前方向盤轉向角度
  private float curDirInDegree;

  public Car(String ownerName) {
    this.ownerName = ownerName;
  }

  public Car(String ownerName, float speed, float dirInDegree) {
    this(ownerName);
    this.curSpeed = speed;
    this.curDirInDegree = dirInDegree;
  }
  // 提供對車主姓名的訪問
  public String getOwnerName() {
    return ownerName;
  }
  // 提供對當前方向盤轉向角度的訪問
  public float getCurDirInDegree() {
    return curDirInDegree;
  }
  // 提供對當前車速的訪問
  public float getCurSpeed() {
    return curSpeed;
  }

  // 提供改變當前的車速
  public void changeSpeed(float curSpeed) {
    // 此處填寫合適的程式碼【2】
    this.curSpeed=curSpeed;
  }

  // 提供停車
  public void stop() {
    // 此處填寫合適的程式碼【3】
      this.curSpeed=0;
      this.curDirInDegree=0;
  }
}

類圖:

分析:該題很簡單,瞭解類和物件的相關知識就能做出了。

  • 7-4答題判題程式-2

設計實現答題程式,模擬一個小型的測試,以下粗體字顯示的是在答題判題程式-1基礎上增補或者修改的內容。
要求輸入題目資訊、試卷資訊和答題資訊,根據輸入題目資訊中的標準答案判斷答題的結果。
輸入格式:
程式輸入資訊分三種,三種資訊可能會打亂順序混合輸入:
1、題目資訊
一行為一道題,可輸入多行資料(多道題)。
格式:"#N:"+題目編號+" "+"#Q:"+題目內容+" "#A:"+標準答案

格式約束:

1、題目的輸入順序與題號不相關,不一定按題號順序從小到大輸入。
2、允許題目編號有缺失,例如:所有輸入的題號為1、2、5,缺少其中的3號題。此種情況視為正常。
樣例:#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
2、試卷資訊
一行為一張試卷,可輸入多行資料(多張卷)。
格式:"#T:"+試卷號+" "+題目編號+"-"+題目分值
題目編號應與題目資訊中的編號對應。
一行資訊中可有多項題目編號與分值。
樣例:#T:1 3-5 4-8 5-2
3、答卷資訊
答卷資訊按行輸入,每一行為一張答卷的答案,每組答案包含某個試卷資訊中的題目的解題答案,答案的順序與試卷資訊中的題目順序相對應。
格式:"#S:"+試卷號+" "+"#A:"+答案內容
格式約束:答案數量可以不等於試卷資訊中題目的數量,沒有答案的題目計0分,多餘的答案直接忽略,答案之間以英文空格分隔。
樣例:#S:1 #A:5 #A:22
1是試卷號
5是1號試卷的順序第1題的題目答案
22是1號試卷的順序第2題的題目答案
答題資訊以一行"end"標記結束,"end"之後的資訊忽略。
輸出格式:
1、試卷總分警示
該部分僅當一張試卷的總分分值不等於100分時作提示之用,試卷依然屬於正常試卷,可用於後面的答題。如果總分等於100分,該部分忽略,不輸出。
格式:"alert: full score of test paper"+試卷號+" is not 100 points"
樣例:alert: full score of test paper2 is not 100 points
2、答卷資訊
一行為一道題的答題資訊,根據試卷的題目的數量輸出多行資料。
格式:題目內容+""+答案++""+判題結果(true/false)

約束:如果輸入的答案資訊少於試卷的題目數量,答案的題目要輸"answer is null"

樣例:3+2=5true

     4+6=~22~false.

  answer is null

3、判分資訊

判分資訊為一行資料,是一條答題記錄所對應試卷的每道小題的計分以及總分,計分輸出的先後順序與題目題號相對應。

格式:題目得分+" "+....+題目得分+"~"+總分

格式約束:

1、沒有輸入答案的題目計0分

2、判題資訊的順序與輸入答題資訊中的順序相同
樣例:5 8 0~13

根據輸入的答卷的數量以上2、3項答卷資訊與判分資訊將重複輸出。

4、提示錯誤的試卷號

如果答案資訊中試卷的編號找不到,則輸出”the test paper number does not exist”,參見樣例9。

設計建議:

參考答題判題程式-1,建議增加答題類,類的內容以及類之間的關聯自行設計。

輸入樣例1:
一張試卷一張答卷。試卷滿分不等於100。例如:

#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
#T:1 1-5 2-8
#S:1 #A:5 #A:22
end

輸出樣例1:
在這裡給出相應的輸出。例如:

alert: full score of test paper1 is not 100 points
1+1=~5~false
2+2=~22~false
0 0~0

輸入樣例2:
一張試卷一張答卷。試卷滿分不等於100。例如:

#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
#T:1 1-70 2-30
#S:1 #A:5 #A:22
end

輸出樣例2:
在這裡給出相應的輸出。例如:

1+1=~5~false
2+2=~22~false
0 0~0

輸入樣例3:
一張試卷、一張答卷。各類資訊混合輸入。例如:

#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
#T:1 1-70 2-30
#N:3 #Q:3+2= #A:5
#S:1 #A:5 #A:4
end

輸出樣例:
在這裡給出相應的輸出。例如:

1+1=~5~false
2+2=~4~true
0 30~30

輸入樣例4:
試卷題目的順序與題號不一致。例如:

#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
#T:1 2-70 1-30
#N:3 #Q:3+2= #A:5
#S:1 #A:5 #A:22
end

輸出樣例:
在這裡給出相應的輸出。例如:

2+2=~5~false
1+1=~22~false
0 0~0

輸入樣例5:
亂序輸入。例如:

#N:3 #Q:3+2= #A:5
#N:2 #Q:2+2= #A:4
#T:1 3-70 2-30
#S:1 #A:5 #A:22
#N:1 #Q:1+1= #A:2
end

輸出樣例:
在這裡給出相應的輸出。例如:

3+2=~5~true
2+2=~22~false
70 0~70

輸入樣例6:
亂序輸入+兩份答卷。例如:

#N:3 #Q:3+2= #A:5
#N:2 #Q:2+2= #A:4
#T:1 3-70 2-30
#S:1 #A:5 #A:22
#N:1 #Q:1+1= #A:2
#S:1 #A:5 #A:4
end

輸出樣例:
在這裡給出相應的輸出。例如:

3+2=~5~true
2+2=~22~false
70 0~70
3+2=~5~true
2+2=~4~true
70 30~100

輸入樣例7:
亂序輸入+分值不足100+兩份答卷。例如:

#N:3 #Q:3+2= #A:5
#N:2 #Q:2+2= #A:4
#T:1 3-7 2-6
#S:1 #A:5 #A:22
#N:1 #Q:1+1= #A:2
#S:1 #A:5 #A:4
end

輸出樣例:
在這裡給出相應的輸出。例如:

alert: full score of test paper1 is not 100 points
3+2=~5~true
2+2=~22~false
7 0~7
3+2=~5~true
2+2=~4~true
7 6~13

輸入樣例8:
亂序輸入+分值不足100+兩份答卷+答卷缺失部分答案。例如:

#N:3 #Q:3+2= #A:5
#N:2 #Q:2+2= #A:4
#T:1 3-7 2-6
#S:1 #A:5 #A:22
#N:1 #Q:1+1= #A:2
#T:2 2-5 1-3 3-2
#S:2 #A:5 #A:4
end

輸出樣例:
在這裡給出相應的輸出。例如:

alert: full score of test paper1 is not 100 points
alert: full score of test paper2 is not 100 points
3+2=~5~true
2+2=~22~false
7 0~7
2+2=~5~false
1+1=~4~false
answer is null
0 0 0~0

輸入樣例9:
亂序輸入+分值不足100+兩份答卷+無效的試卷號。例如:

#N:3 #Q:3+2= #A:5
#N:2 #Q:2+2= #A:4
#T:1 3-7 2-6
#S:3 #A:5 #A:4
end

輸出樣例:
在這裡給出相應的輸出。例如:

alert: full score of test paper1 is not 100 points
The test paper number does not exist

原始碼:

點選檢視程式碼
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

class Question{
    private int number;
    private String content;
    private String standardAnswer;
    public Question(){
    	
    }
    
    public Question(int number, String content, String standardAnswer) {
        this.number = number;
        this.content = content;
        this.standardAnswer = standardAnswer;
    }
    
    public void setNumber(int number){
        this.number=number;
    }
    
    public void setContent(String content) {
       this.content = content;
    }
    
    public void setStandardAnswer(String standardAnswer) {
        this.standardAnswer = standardAnswer;
    }
    
    public int getNumber() {
        return number;
    }
    
    public String getContent() {
        return content;
    }
    
    public String getStandardAnswer() {
        return standardAnswer;
    }
   
    public boolean checkAnswer(String answer) {
        return answer.equals(standardAnswer);
    }
}

class ExaminationPaper{
    private int number;
    private List<Question>questionList;
    private List<Integer>scorelist= new ArrayList<>();
    private int questionCount;
    public ExaminationPaper(){
        this.questionList= new ArrayList<>();
    }
    public ExaminationPaper(int questionCount) {
        this.questionList = new ArrayList<>(questionCount);
        this.setQuestionCount(questionCount);
    }
    public void addScore(int n,int score){
        this.scorelist.add(n,score);
    }
    public int getScore(int n){
        return this.scorelist.get(n);
    }
    public void setNumber(int number){
        this.number=number;
    }
    public int getNumber(){
        return this.number;
    }
    public void addQuestion(int n,Question question) {
        questionList.add(n,question);
    }
    public boolean checkAnswer(int num,String answer){
        Question question = questionList.get(num);
        return question.checkAnswer(answer);
    }
    public Question question(int num){
        return questionList.get(num);
    }
	public int getQuestionCount() {
		return questionCount;
	}
	public void setQuestionCount(int questionCount) {
		this.questionCount = questionCount;
	}
    public int sumOfQuestions(){
        int sum=0;
        for(int i=0;i<questionCount;i++){
            sum+=scorelist.get(i);
        }
        return sum;
    }
    public void scoreWarning(){
        if(this.sumOfQuestions()!=100)
            System.out.println("alert: full score of test paper"+this.number+" is not 100 points"); 
    }
}

class Answer{
    private ExaminationPaper test;
    private List<String>answers=new ArrayList<>();;
    private List<Boolean>results=new ArrayList<>();;
    private int number;
    private int num;
    private boolean paperIsExist;
    public Answer() {
    	this.paperIsExist=false;
    }
    public int getTestQuestionCount(){
        return this.test.getQuestionCount();
    }
    public boolean getPaperIsExist(){
        return this.paperIsExist;
    }
    public void PaperIsExist(){
        if(this.test==null)
            this.paperIsExist=false;
        else
            this.paperIsExist=true;
    }
    
    public Answer(ExaminationPaper test,int questionCount){
        this.test=test;
        this.answers = new ArrayList<>(questionCount);
        this.results = new ArrayList<>(questionCount);
    }
    public void setResultSize(int size){
        this.results = new ArrayList<>(size);
    }
    public void setTest(ExaminationPaper test){
        this.test=test;
    }
    public void setNum(int num){
        this.num=num;
    }
    public int getNum(){
        return this.num;
    }
    public void setNumber(int number){
        this.number=number;
    }
    public int getNumber(){
        return this.number;
    }
    public void addAnswer(int n,String answer){
    	this.answers.add(n,answer);
    }
    public String getAnswer(int n){
        return this.answers.get(n);
    }
    public void addResults(int n){
    	this.results.add(n,this.test.checkAnswer(n,answers.get(n)));
    }
    public void questionscore(int n){
        int sum=0;
        for(int i=0;i<n;i++){
            if(this.results.get(i)){
                sum+=this.test.getScore(i);
                System.out.printf("%d",this.test.getScore(i));
                if(i!=n-1){
                    System.out.print(" ");
                }
            }
            else{
                System.out.print("0");
                if(i!=n-1){
                    System.out.print(" ");
                }
            }
        }
        if(this.test.getQuestionCount()>n){
            for(int i=0;i<this.test.getQuestionCount()-n;i++){
                System.out.print(" "+"0");
            }
        }
        System.out.print("~"+sum+"\n");
    }
    public void printResult(int n){
        for(int i=0;i<n;i++){
            System.out.printf("%s~%s~%s\n",this.test.question(i).getContent(),this.answers.get(i),this.results.get(i));
        }
        if(this.test.getQuestionCount()>n){
            for(int i=0;i<this.test.getQuestionCount()-n;i++){
                System.out.println("answer is null");
            }
        }
        this.questionscore(n);
    }
}

public class Main{
    public static void main(String [] args){
        Scanner input =new Scanner(System.in);
        String []line=new String[200];
        List<String>str1=new ArrayList<String>();
        List<String>str2=new ArrayList<String>();
        List<String>str3=new ArrayList<String>();
        Pattern pattern1 = Pattern.compile("#N:.*#Q:.*#A:");
        Pattern pattern2 = Pattern.compile("#T:.*");
        Pattern pattern3 = Pattern.compile("#S:.*#A:.*");
        int i=0;
        int numOfQuestion=0;
        int numOfExaminationPaper=0;
        int numOfAnswer=0;
        while(input.hasNextLine()){
            line[i]=input.nextLine();
            if(line[i].equals("end")){
                break;
            }
            Matcher matcher1 = pattern1.matcher(line[i]);
            Matcher matcher2 = pattern2.matcher(line[i]);
            Matcher matcher3 = pattern3.matcher(line[i]);
            if(matcher1.find()){
                numOfQuestion++;
                str1.add(line[i]);
            }
            else if(matcher2.find()){
                numOfExaminationPaper++;
                str2.add(line[i]);
            }
            else if(matcher3.find()){
                numOfAnswer++;
                str3.add(line[i]);
            }
            i++;
        }
        
        int maxOfQuestion=0;
        for(int j=0;j<numOfQuestion;j++){
            int number=0;
            Pattern pattern = Pattern.compile("#N:\\s*(\\d+)\\s*#Q:\\s*(.*?)\\s*#A:\\s*(.*)\\s*");
            Matcher matcher = pattern.matcher(str1.get(j));
            if(matcher.find()){
                number = Integer.parseInt(matcher.group(1).trim());
            }
            if(maxOfQuestion<number)
                maxOfQuestion=number;
        }
        Question []questions=new Question[maxOfQuestion];
        for(int j=0;j<maxOfQuestion;j++){
             questions[j]=new Question();
        }
        for(int j=0;j<numOfQuestion;j++){
            int number=0;
            String content;
            String standardAnswer;
            Pattern pattern = Pattern.compile("#N:\\s*(\\d+)\\s*#Q:\\s*(.*?)\\s*#A:\\s*(.*)\\s*");
            Matcher matcher = pattern.matcher(str1.get(j));
            if(matcher.find()){
                number = Integer.parseInt(matcher.group(1).trim());
                content= matcher.group(2).trim();
                standardAnswer = matcher.group(3).trim();
                int c=number-1;
                questions[c]=new Question(number,content,standardAnswer);
            }
        }
        ExaminationPaper []test=new ExaminationPaper[numOfExaminationPaper];
        for(int j=0;j<numOfExaminationPaper;j++){
            int count=0;
            test[j]=new ExaminationPaper();
            Pattern pattern = Pattern.compile("#T:\\s*(\\d+)\\s*(.*)");
            Matcher matcher = pattern.matcher(str2.get(j));
            if(matcher.find()){
                int number = Integer.parseInt(matcher.group(1).trim());
                test[j].setNumber(number);
                String text=matcher.group(2).trim();
                String []parts1=text.split("\\s+");
                int []numberOfQuestion2=new int [parts1.length];
                int []scoresOfQuestion=new int [parts1.length];
                for(int ii=0;ii<parts1.length;ii++){
                    String []parts2=parts1[ii].split("-");
                    numberOfQuestion2[ii]=Integer.parseInt(parts2[0]);                        
                    scoresOfQuestion[ii]=Integer.parseInt(parts2[1]);
                    count++;
                }
                
                for(int k=0;k<parts1.length;k++){
                    test[j].addQuestion(k,questions[numberOfQuestion2[k]-1]);
                    test[j].addScore(k,scoresOfQuestion[k]);
                }   
                
            }
            test[j].setQuestionCount(count);
        }  

        
        Answer []answer=new Answer[numOfAnswer];
        for(int j=0;j<numOfAnswer;j++){
            answer[j]=new Answer();
        }
        for(int j=0;j<numOfAnswer;j++){
            int number=0;
            String text;
            Pattern pattern = Pattern.compile("#S:\\s*(\\d+)\\s*(.*)");
            Matcher matcher = pattern.matcher(str3.get(j));
            
            if(matcher.find()){
                int size=0;
                number = Integer.parseInt(matcher.group(1).trim());
                for(int k=0;k<numOfExaminationPaper;k++){
                    if(number==test[k].getNumber()){
                        answer[j].setTest(test[k]);
                        answer[j].PaperIsExist();
                        break;
                    }
                }
                answer[j].setNumber(number);
                text=matcher.group(2).trim();
                String text1=text.replaceAll("#A:","");
                String []answers=text1.split("\\s+");
                if(answer[j].getPaperIsExist()){
                    size=answer[j].getTestQuestionCount();
                    for(int k=0;k<(size<answers.length?size:answers.length);k++){
                        answer[j].addAnswer(k,answers[k]);
                    }
                }
                answer[j].setNum((size<answers.length?size:answers.length));
            }
        }
        for(int j=0;j<numOfAnswer;j++){
            if(answer[j].getPaperIsExist()){
                answer[j].setResultSize(answer[j].getNum());
                for(int k=0;k<answer[j].getNum();k++){
                    answer[j].addResults(k);
                }
            }
            
        }
        for(int j=0;j<numOfExaminationPaper;j++){
            test[j].scoreWarning();
        }
        for(int j=0;j<numOfAnswer;j++){
            if(answer[j].getPaperIsExist()){
                answer[j].printResult(answer[j].getNum());
            }
            else{
                System.out.println("The test paper number does not exist");
            }
        }
    }
}

類圖:

分析:先用正規表示式對輸入的每行字串進行分類,分為題目,試卷,答卷三種資訊。再依次對題目試卷答卷類字串進行拆分,設定到題目,試卷,答卷中。再對答案進行校驗,最後先輸出分數提示,再輸出答卷及判分資訊。

第三次題目集

  • 7-1物件導向程式設計(封裝性)
    原始碼:
點選檢視程式碼

import java.util.*;

class Student{
    private String sid;
    private String name;
    private int age;
    private String major;

    public Student(){
        
    }
    public Student(String sid,String name,int age,String major){
        this.setSid(sid);
        this.setName(name);
        this.setAge(age);
        this.setMajor(major);
    }
	public String getID() {
		return sid;
	}
	public void setSid(String sid) {
		this.sid = sid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		if(age>=0){
            this.age=age;
        }
	}
	public String getMajor() {
		return major;
	}
	public void setMajor(String major) {
		this.major = major;
	}
    public void print(){
        System.out.println("學號:"+sid+",姓名:"+name+",年齡:"+age+",專業:"+major);
    }
}
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //呼叫無參構造方法,並透過setter方法進行設值
        String sid1 = sc.next();
        String name1 = sc.next();
        int age1 = sc.nextInt();
        String major1 = sc.next();
        Student student1 = new Student();
        student1.setSid(sid1);
        student1.setName(name1);
        student1.setAge(age1);
        student1.setMajor(major1);
        //呼叫有參構造方法
        String sid2 = sc.next();
        String name2 = sc.next();
        int age2 = sc.nextInt();
        String major2 = sc.next();
        Student student2 = new Student(sid2, name2, age2, major2);
        //對學生student1和學生student2進行輸出
        student1.print();
        student2.print();
    }
}

/* 請在這裡填寫答案 */

類圖:

分析:該題很簡單,瞭解類和物件的相關知識就能做出了。

  • 7-2 jmu-java-日期類的基本使用
    原始碼:
點選檢視程式碼
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        String dateStr1 = input.nextLine();
        String dateStr2 = input.nextLine();
        if (!isValidDate(dateStr1)) {
            System.out.println(dateStr1 + "無效!");
        } 
        else { 
            Date date1 = parseDate(dateStr1);
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(date1);
            int year = calendar1.get(Calendar.YEAR);
            boolean isLeapYear = isLeapYear(year);
            if(isLeapYear){
                System.out.println(dateStr1 +"是閏年.");
            }
            int week=calendar1.get(Calendar.DAY_OF_WEEK);
            if(week==1){
                 week=7;
            }
            else{
                week-=1;
            }   
            System.out.println(dateStr1 + "是當年第" + calendar1.get(Calendar.DAY_OF_YEAR) + "天,當月第" + calendar1.get(Calendar.DAY_OF_MONTH) + "天,當週第" + week + "天.");
        }

        
        String[] dates = dateStr2.split(" ");
        boolean isValid = true;
        for (int i=0;i<=1;i++) {
            if (!isValidDate(dates[i])) {
                isValid = false;
                break;
            }
        }
        if(isValid==false){
            System.out.println(dates[0]+"或" +dates[1]+ "中有不合法的日期.");
        }
        
        if (isValid && compareDates(dates[0], dates[1]) <= 0) {
            Date startDate = parseDate(dates[0]);
            Date endDate = parseDate(dates[1]);
            long diffDays = getDifferenceInDays(startDate, endDate);
            int diffMonths = getDifferenceInMonths(startDate,endDate);
            int diffYears = getDifferenceInYears(startDate, endDate);
            System.out.printf("%s與%s之間相差%d天,所在月份相差%d,所在年份相差%d.",dates[1],dates[0],diffDays,diffMonths,diffYears);
        }
        if (isValid){
            warnning(dates[0],dates[1]);
        }
        
    }
    public static boolean isValidDate(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
        Matcher matcher = pattern.matcher(dateStr);
        if(matcher.find()&&dateStr.length()==10){
            sdf.setLenient(false);
            try {
                sdf.parse(dateStr);
                return true;
            } catch (ParseException e) {
                return false;
            }
        }
        else{
            return false;
        }
        
    }

    
    public static Date parseDate(String dateStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }

    
    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }

   
    public static int compareDates(String dateStr1, String dateStr2) {
        Date date1 = parseDate(dateStr1);
        Date date2 = parseDate(dateStr2);
        return date1.compareTo(date2);
    }

  
    public static long getDifferenceInDays(Date startDate, Date endDate) {
        long diff = endDate.getTime() - startDate.getTime();
        return diff / (24 * 60 * 60 * 1000);
    }

    
    public static int getDifferenceInMonths(Date startDate, Date endDate) {
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(startDate);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDate);

        int diffYears = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
        int diffMonths = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
        return /*diffYears * 12+*/  diffMonths;
    }
    public static int getDifferenceInYears(Date startDate, Date endDate) {
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(startDate);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDate);
        return endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
    }
    public static void warnning(String data1,String data2){
        Date startDate = parseDate(data1);
        Date endDate = parseDate(data2);
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(startDate);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDate);
        if(endCalendar.before(startCalendar)){
            System.out.print(data2+"早於"+data1+",不合法!");
        }
    }
}

分析:主要考察了日期類中相關方法的使用

  • 7-3 答題判題程式-3
    設計實現答題程式,模擬一個小型的測試,以下粗體字顯示的是在答題判題程式-2基礎上增補或者修改的內容,要求輸入題目資訊、試卷資訊、答題資訊、學生資訊、刪除題目資訊,根據輸入題目資訊中的標準答案判斷答題的結果。

輸入格式:

程式輸入資訊分五種,資訊可能會打亂順序混合輸入。

1、題目資訊
題目資訊為獨行輸入,一行為一道題,多道題可分多行輸入。

格式:"#N:"+題目編號+" "+"#Q:"+題目內容+" "#A:"+標準答案

格式約束:
1、題目的輸入順序與題號不相關,不一定按題號順序從小到大輸入。
2、允許題目編號有缺失,例如:所有輸入的題號為1、2、5,缺少其中的3號題。此種情況視為正常。
樣例:#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4

2、試卷資訊

試卷資訊為獨行輸入,一行為一張試卷,多張卷可分多行輸入資料。
格式:"#T:"+試卷號+" "+題目編號+"-"+題目分值+" "+題目編號+"-"+題目分值+...

格式約束:
題目編號應與題目資訊中的編號對應。
一行資訊中可有多項題目編號與分值。
樣例:#T:1 3-5 4-8 5-2

3、學生資訊

學生資訊只輸入一行,一行中包括所有學生的資訊,每個學生的資訊包括學號和姓名,格式如下。

格式:"#X:"+學號+" "+姓名+"-"+學號+" "+姓名....+"-"+學號+" "+姓名

格式約束:
答案數量可以不等於試卷資訊中題目的數量,沒有答案的題目計0分,多餘的答案直接忽略,答案之間以英文空格分隔。
樣例:
#S:1 #A:5 #A:22
1是試卷號
5是1號試卷的順序第1題的題目答案
4、答卷資訊

答卷資訊按行輸入,每一行為一張答卷的答案,每組答案包含某個試卷資訊中的題目的解題答案,答案的順序號與試 卷資訊中的題目順序相對應。答卷中:

格式:"#S:"+試卷號+" "+學號+" "+"#A:"+試卷題目的順序號+"-"+答案內容+...

格式約束:
答案數量可以不等於試卷資訊中題目的數量,沒有答案的題目計0分,多餘的答案直接忽略,答案之間以英文空格分隔。
答案內容可以為空,即””。
答案內容中如果首尾有多餘的空格,應去除後再進行判斷。
樣例:
#T:1 1-5 3-2 2-5 6-9 4-10 7-3
#S:1 20201103 #A:2-5 #A:6-4
1是試卷號
20201103是學號
2-5中的2是試卷中順序號,5是試卷第2題的答案,即T中3-2的答案
6-4中的6是試卷中順序號,4是試卷第6題的答案,即T中7-3的答案
注意:不要混淆順序號與題號

5、刪除題目資訊

刪除題目資訊為獨行輸入,每一行為一條刪除資訊,多條刪除資訊可分多行輸入。該資訊用於刪除一道題目資訊,題目被刪除之後,引用該題目的試卷依然有效,但被刪除的題目將以0分計,同時在輸出答案時,題目內容與答案改為一條失效提示,例如:”the question 2 invalid~0”

格式:"#D:N-"+題目號

格式約束:

   題目號與第一項”題目資訊”中的題號相對應,不是試卷中的題目順序號。

   本題暫不考慮刪除的題號不存在的情況。      

樣例:

#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
#T:1 1-5 2-8
#X:20201103 Tom-20201104 Jack
#S:1 20201103 #A:1-5 #A:2-4
#D:N-2
end

輸出

alert: full score of test paper1 is not 100 points
1+1=~5~false
the question 2 invalid~0
20201103 Tom: 0 0~0
 答題資訊以一行"end"標記結束,"end"之後的資訊忽略。

輸出格式:

1、試卷總分警示

該部分僅當一張試卷的總分分值不等於100分時作提示之用,試卷依然屬於正常試卷,可用於後面的答題。如果總分等於100 分,該部分忽略,不輸出。

格式:"alert: full score of test paper"+試卷號+" is not 100 points"

樣例:alert: full score of test paper2 is not 100 points

2、答卷資訊

一行為一道題的答題資訊,根據試卷的題目的數量輸出多行資料。

格式:題目內容+""+答案++""+判題結果(true/false)

約束:如果輸入的答案資訊少於試卷的題目數量,答案的題目要輸"answer is null"
樣例:

    3+2=~5~true
     4+6=~22~false.
     answer is null

3、判分資訊
判分資訊為一行資料,是一條答題記錄所對應試卷的每道小題的計分以及總分,計分輸出的先後順序與題目題號相對應。
格式:學號+" "+姓名+": "+題目得分+" "+....+題目得分+"~"+總分
格式約束:

1、沒有輸入答案的題目、被刪除的題目、答案錯誤的題目計0分
  2、判題資訊的順序與輸入答題資訊中的順序相同
 樣例:20201103 Tom: 0 0~0
    根據輸入的答卷的數量以上2、3項答卷資訊與判分資訊將重複輸出。

4、被刪除的題目提示資訊
當某題目被試卷引用,同時被刪除時,答案中輸出提示資訊。樣例見第5種輸入資訊“刪除題目資訊”。

5、題目引用錯誤提示資訊
試卷錯誤地引用了一道不存在題號的試題,在輸出學生答案時,提示”non-existent question~”加答案。例如:

輸入:

#N:1 #Q:1+1= #A:2
#T:1 3-8
#X:20201103 Tom-20201104 Jack-20201105 Www
#S:1 20201103 #A:1-4
end

輸出:

alert: full score of test paper1 is not 100 points
non-existent question~0
20201103 Tom: 0~0

如果答案輸出時,一道題目同時出現答案不存在、引用錯誤題號、題目被刪除,只提示一種資訊,答案不存在的優先順序最高,例如:
輸入:

#N:1 #Q:1+1= #A:2
#T:1 3-8
#X:20201103 Tom-20201104 Jack-20201105 Www
#S:1 20201103
end

輸出:

alert: full score of test paper1 is not 100 points
answer is null
20201103 Tom: 0~0

6、格式錯誤提示資訊

輸入資訊只要不符合格式要求,均輸出”wrong format:”+資訊內容。

 ` 例如:wrong format:2 #Q:2+2= #4`

7、試卷號引用錯誤提示輸出

如果答卷資訊中試卷的編號找不到,則輸出”the test paper number does not exist”,答卷中的答案不用輸出,參見樣例8。

8、學號引用錯誤提示資訊

如果答卷中的學號資訊不在學生列表中,答案照常輸出,判分時提示錯誤。參見樣例9。

本題暫不考慮出現多張答卷的資訊的情況。

輸入樣例1:
簡單輸入,不含刪除題目資訊。例如:

#N:1 #Q:1+1= #A:2
#T:1 1-5
#X:20201103 Tom
#S:1 20201103 #A:1-5
end

輸出樣例1:
在這裡給出相應的輸出。例如:

alert: full score of test paper1 is not 100 points
1+1=~5~false
20201103 Tom: 0~0

輸入樣例2:
簡單輸入,答卷中含多餘題目資訊(忽略不計)。例如:

#N:1 #Q:1+1= #A:2
#T:1 1-5
#X:20201103 Tom
#S:1 20201103 #A:1-2 #A:2-3
end

輸出樣例3
簡單測試,含刪除題目資訊。例如:

alert: full score of test paper1 is not 100 points
1+1=~2~true
20201103 Tom: 5~5

輸入樣例3:
簡單測試,含刪除題目資訊。例如:

#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
#T:1 1-5 2-8
#X:20201103 Tom-20201104 Jack-20201105 Www
#S:1 20201103 #A:1-5 #A:2-4
#D:N-2
end

輸出樣例3:
在這裡給出相應的輸出,第二題由於被刪除,輸出題目失效提示。例如:

alert: full score of test paper1 is not 100 points
1+1=~5~false
the question 2 invalid~0
20201103 Tom: 0 0~0

輸入樣例4:
簡單測試,含試卷無效題目的引用資訊以及刪除題目資訊(由於題目本身無效,忽略)。例如:

#N:1 #Q:1+1= #A:2
#N:2 #Q:2+2= #A:4
#T:1 1-5 3-8
#X:20201103 Tom-20201104 Jack-20201105 Www
#S:1 20201103 #A:1-5 #A:2-4
#D:N-2
end

輸出樣例4:
輸出不存在的題目提示資訊。例如:

alert: full score of test paper1 is not 100 points
1+1=~5~false
non-existent question~0
20201103 Tom: 0 0~0

輸入樣例5:
綜合測試,含錯誤格式輸入、有效刪除以及無效題目引用資訊。例如:

#N:1 +1= #A:2
#N:2 #Q:2+2= #A:4
#T:1 1-5 2-8
#X:20201103 Tom-20201104 Jack-20201105 Www
#S:1 20201103 #A:1-5 #A:2-4
#D:N-2
end

輸出樣例5:
在這裡給出相應的輸出。例如:

wrong format:#N:1 +1= #A:2
alert: full score of test paper1 is not 100 points
non-existent question~0
the question 2 invalid~0
20201103 Tom: 0 0~0

輸入樣例6:
綜合測試,含錯誤格式輸入、有效刪除、無效題目引用資訊以及答案沒有輸入的情況。例如:

#N:1 +1= #A:2
#N:2 #Q:2+2= #A:4
#T:1 1-5 2-8
#X:20201103 Tom-20201104 Jack-20201105 Www
#S:1 20201103 #A:1-5
#D:N-2
end

輸出樣例6:
答案沒有輸入的優先順序最高。例如:

wrong format:#N:1 +1= #A:2
alert: full score of test paper1 is not 100 points
non-existent question~0
answer is null
20201103 Tom: 0 0~0

輸入樣例7:
綜合測試,正常輸入,含刪除資訊。例如:

#N:2 #Q:2+2= #A:4
#N:1 #Q:1+1= #A:2
#T:1 1-5 2-8
#X:20201103 Tom-20201104 Jack-20201105 Www
#S:1 20201103 #A:2-4 #A:1-5
#D:N-2
end

輸出樣例7:
例如:

alert: full score of test paper1 is not 100 points
1+1=~5~false
the question 2 invalid~0
20201103 Tom: 0 0~0

輸入樣例8:
綜合測試,無效的試卷引用。例如:

#N:1 #Q:1+1= #A:2
#T:1 1-5
#X:20201103 Tom
#S:2 20201103 #A:1-5 #A:2-4
end

輸出樣例8:
例如:

alert: full score of test paper1 is not 100 points
The test paper number does not exist

輸入樣例9:
無效的學號引用。例如:

#N:1 #Q:1+1= #A:2
#T:1 1-5
#X:20201106 Tom
#S:1 20201103 #A:1-5 #A:2-4
end

輸出樣例9:
答案照常輸出,判分時提示錯誤。例如:

alert: full score of test paper1 is not 100 points
1+1=~5~false
20201103 not found

輸入樣例10:
資訊可打亂順序輸入:序號不是按大小排列,各類資訊交錯輸入。但本題不考慮引用的題目在被引用的資訊之後出現的情況(如試卷引用的所有題目應該在試卷資訊之前輸入),所有引用的資料應該在被引用的資訊之前給出。例如:

#N:3 #Q:中國第一顆原子彈的爆炸時間 #A:1964.10.16
#N:1 #Q:1+1= #A:2
#X:20201103 Tom-20201104 Jack-20201105 Www
#T:1 1-5 3-8
#N:2 #Q:2+2= #A:4
#S:1 20201103 #A:1-5 #A:2-4
end

輸出樣例10:
答案按試卷中的題目順序輸出。例如:

alert: full score of test paper1 is not 100 points
1+1=~5~false
中國第一顆原子彈的爆炸時間~4~false
20201103 Tom: 0 0~0

原始碼:

點選檢視程式碼
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Question {
	private int number=0;
	private String content;
	private String standarAnswer;
	private boolean isDelect=false;
	
	public Question() {
		
	}
	public Question(int number,String content,String standarAnswer) {
		this.number=number;
		this.content=content;
		this.standarAnswer=standarAnswer;
	}
	
	public int getNumber() {
		return this.number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
	public String getContent() {
		return this.content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getStandarAnswer() {
		return this.standarAnswer;
	}
	public void setStandarAnswer(String standarAnswer) {
		this.standarAnswer = standarAnswer;
	}
	public boolean getDelect() {
		return this.isDelect;
	}
	public void setDelect(int number) {
		if(this.number==number) {
			this.isDelect=true;
		}
	}
	public boolean checkAnswer(String answer) {
		if(this.standarAnswer.equals(answer)) {
			return true;
		}
		else
			return false;
	}
}

class Student {
	private List<Integer>ID=new ArrayList<>();
	private List<String>name=new ArrayList<>();
	public Student() {
		
	}
	public int getID(int index) {
		return this.ID.get(index);
	}
	public void addID(int ID) {
		this.ID.add(ID);
	}
	public String getName(int index) {
		return this.name.get(index);
	}
	public void addName(String name) {
		this.name.add(name);
	}
	public int getIDSize() {
		return this.ID.size();
	}
}

class Paper {
	private int number=0;
	private List<Question>questions= new ArrayList<>();
	private List<Integer>questoinScores=new ArrayList<>();
	public Paper() {
		
	}
	public Paper(int number) {
		this.number=number;
	}
	
	public int getNumber() {
		return this.number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
	public void addQuestions(Question question) {
		this.questions.add(question);
	}
	public Question getQuestions(int index) {
		return this.questions.get(index);
	}
	public void addQuestoinScores(int score) {
		this.questoinScores.add(score);
	}
	public int getQuestoinScores(int index) {
		return this.questoinScores.get(index);
	}
	public List<Integer> getQuestoinScores() {
		return questoinScores;
	}
	public List<Question>getQuestions(){
		return this.questions;
	}
	
}

class StudentAnswer {
	private int studentID;
	private List<Integer>questionsNumber=new ArrayList<>();
	private List<String>questionsAnswer=new ArrayList<>();
	public StudentAnswer() {
		
	}
	public StudentAnswer(int studentID) {
		this.setStudentID(studentID);
	}
	public int getStudentID() {
		return studentID;
	}
	public void setStudentID(int studentID) {
		this.studentID = studentID;
	}
	public void addQuestionsAnswer(String answer) {
		this.questionsAnswer.add(answer);
	}
	public String getQuestionsAnswer(int index) {
		return this.questionsAnswer.get(index);
	}
	public int getQuestionsNumber(int index) {
		return questionsNumber.get(index);
	}
	public void addQuestionsNumber(int number) {
		this.questionsNumber.add(number);
	}
	public List<String> getQuestionsAnswer() {
		return this.questionsAnswer;
	}
}

class PaperAnswer {
	private int number=0;
	private Paper test;
	private List<StudentAnswer>studentsAnswer=new ArrayList<>();
	public PaperAnswer() {
		
	}
	public PaperAnswer(int number,Paper test) {
		this.setNumber(number);
		this.setTest(test);
	}
	public int getNumber() {
		return number;
	}
	public void setNumber(int number) {
		this.number = number;
	}
	public void addStudentsAnswer(StudentAnswer answer) {
		this.studentsAnswer.add(answer);
	}
	public StudentAnswer getStudentsAnswer(int index) {
		return this.studentsAnswer.get(index);
	}
	public Paper getTest() {
		return test;
	}
	public void setTest(Paper test) {
		this.test = test;
	}
	public List<StudentAnswer> getstudentsAnswer() {
		return this.studentsAnswer;
	}
}
class View {
	public void scoreWarnning(Paper testPaper) {
		int sum=0;
		for(int i=0;i<testPaper.getQuestoinScores().size();i++) {
			sum+=testPaper.getQuestoinScores(i);
		}
		if(sum!=100) {
			System.out.println("alert: full score of test paper"+testPaper.getNumber()+" is not 100 points");
		}
	}
	public void answerInformation(PaperAnswer paperAnswer,Student students) {
		if(paperAnswer.getTest()==null) {
			System.out.println("The test paper number does not exist");
		}
		else {
			for(int i=0;i<paperAnswer.getstudentsAnswer().size();i++) {
				int n1=paperAnswer.getTest().getQuestions().size();//題目個數
				int n2=paperAnswer.getStudentsAnswer(i).getQuestionsAnswer().size();//答案個數
				int []score=new int[n1];
				if(n1<=n2) {
					for(int j=0;j<n1;j++) {
						if(paperAnswer.getTest().getQuestions(j)!=null) {
							int questionNUmber=paperAnswer.getStudentsAnswer(i).getQuestionsNumber(j);
							String str1=paperAnswer.getTest().getQuestions(j).getContent();
							String str2=paperAnswer.getStudentsAnswer(i).getQuestionsAnswer(questionNUmber-1);
							boolean result=paperAnswer.getTest().getQuestions(j).checkAnswer(str2);
							boolean isdeldect=paperAnswer.getTest().getQuestions(j).getDelect();
							if(isdeldect) {
								System.out.println("the question "+paperAnswer.getTest().getQuestions(j).getNumber()+" invalid~0");//被刪除的題目提示資訊
								score[j]=0;
							}
							else {
								System.out.println(str1+"~"+str2+"~"+result);
								if(result) {
									score[j]=paperAnswer.getTest().getQuestoinScores(j);
								}
								else {
									score[j]=0;
								}
							}
						}
						else {
							System.out.println("non-existent question~0");
							score[j]=0;
						}
					}
				}
				else {
                    int []arr=new int[n2];
						for(int j=0;j<n2;j++) {
							arr[j]=paperAnswer.getStudentsAnswer(i).getQuestionsNumber(j);
						}
						for(int j=0;j<n1;j++) {
                            int flag=0;
							for(int k=0;k<n2;k++) {
								if(j==(arr[k]-1)) {
                                    flag=1;
									if(paperAnswer.getTest().getQuestions(j)!=null) {
											String str1=paperAnswer.getTest().getQuestions(j).getContent();
											String str2=paperAnswer.getStudentsAnswer(i).getQuestionsAnswer(k);
											boolean result=paperAnswer.getTest().getQuestions(j).checkAnswer(str2);
											boolean isdeldect=paperAnswer.getTest().getQuestions(j).getDelect();
											if(isdeldect) {
												System.out.println("the question "+paperAnswer.getTest().getQuestions(j).getNumber()+" invalid~0");
												score[j]=0;
											}
											else {
												System.out.println(str1+"~"+str2+"~"+result);
												if(result) {
													score[j]=paperAnswer.getTest().getQuestoinScores(j);
												}
												else {
													score[j]=0;
												}
											}
									}
									else {
										System.out.println("non-existent question~0");
										score[j]=0;	
									}	
								}
							}
                            if(flag==0){
                                System.out.println("answer is null");
                            }
                            
						}
				}
				int ID=paperAnswer.getStudentsAnswer(i).getStudentID();
				int flag=0;
				int sum=0;
				for(int j=0;j<students.getIDSize();j++) {
					if(ID==students.getID(j)) {
						System.out.print(students.getID(j)+" "+students.getName(j)+": ");//學號姓名
						flag=1;
						break;
					}
				}
				if(flag==0) {
					System.out.println(ID+" not found");
				}
				else {
					for(int k=0;k<(n1);k++) {
						System.out.print(score[k]);
						sum+=score[k];
						if(k!=(n1-1)) {
							System.out.print(" ");
						}
					}
					System.out.println("~"+sum);
				}
			}
		}
	}
}


public class Main {
	public static void main(String[] args) {
		Scanner input=new Scanner(System.in);
		
		String []line=new String[200];
		
        List<String>str1=new ArrayList<String>();//題目資訊
        List<String>str2=new ArrayList<String>();//試卷資訊
        String str3=new String();//學生資訊
        List<String>str4=new ArrayList<String>();//答卷資訊
        List<String>str5=new ArrayList<String>();//刪除題目資訊
        
        Pattern pattern1 = Pattern.compile("#N:.*#Q:.*#A:.*");
        Pattern pattern2 = Pattern.compile("#T:\\d+\\s+(.*)");
        Pattern pattern3 = Pattern.compile("#X:(.*)");
        Pattern pattern4 = Pattern.compile("#S:\\d+\\s*\\d+\\s*(.*)");
        Pattern pattern5 = Pattern.compile("#D:N-\\d+");
        int i=0;
        int n1=0;//題目數量
        int n2=0;//試卷數量
        //n3=1
        int n4=0;//答卷數量
        int n5=0;//刪除題目數量
        while(input.hasNextLine()){
            line[i]=input.nextLine();
            if(line[i].equals("end")){
                break;
            }
            Matcher matcher1 = pattern1.matcher(line[i]);
            Matcher matcher2 = pattern2.matcher(line[i]);
            Matcher matcher3 = pattern3.matcher(line[i]);
            Matcher matcher4 = pattern4.matcher(line[i]);
            Matcher matcher5 = pattern5.matcher(line[i]);
            if(matcher1.find()){
                if(matcher1.group().length()==line[i].length()){
                    n1++;
                    str1.add(line[i]);
                }
                else{
                    System.out.println("wrong format:"+line[i]);
                }
                
            }
            else if(matcher2.find()){
                if(matcher2.group(1).equals("")) {
                	n2++;
                    str2.add(line[i]);
                    continue;
                }
                Pattern pattern = Pattern.compile("\\d+-\\d+\\s*");
                Matcher matcher = pattern.matcher(matcher2.group(1));
                int size1=0;
                while (matcher.find()) {
                    size1+=matcher.group(0).length();
                }
                if(size1==matcher2.group(1).length()){
                    n2++;
                    str2.add(line[i]);
                }
                else{
                    System.out.println("wrong format:"+line[i]);
                }
            }
            else if(matcher3.find()){
                Pattern pattern = Pattern.compile("\\d+\\s+[a-zA-Z]*-*");
                Matcher matcher = pattern.matcher(matcher3.group(1));
                int size1=0;
                while (matcher.find()) {
                    size1+=matcher.group(0).length();
                }
                if(size1==matcher3.group(1).length()){
                    str3=new String(line[i]);
                }
                else{
                    System.out.println("wrong format:"+line[i]);
                }
                
                
            }///答案為空字元
            else if(matcher4.find()){
                Pattern pattern = Pattern.compile("#A:\\s*(\\d+)\\s*-(.*?)\\s*(?=#A:|\\n|$)");
                Matcher matcher = pattern.matcher(matcher4.group(1));
                int size1=0;
                while (matcher.find()) {
                    size1+=matcher.group(0).length();
                }
                if(size1==matcher4.group(1).length()){
                    n4++;
                    str4.add(line[i]);
                }
                else{
                    System.out.println("wrong format:"+line[i]);
                }
            }
            else if(matcher5.find()){
            	n5++;
            	str5.add(line[i]);
            }
            else {
            	System.out.println("wrong format:"+line[i]);
            }
            i++;
        }
        input.close();
        //學生資訊
        Student students=new Student();
        for(int j=0;j<1;j++) {
        	Pattern pattern = Pattern.compile("#X:(.*)");
            Matcher matcher = pattern.matcher(str3);
            if(matcher.find()) {
            	String text=matcher.group(1);
            	text=text.replaceAll("-", " ");
            	text=text.trim();
            	String []IDandName=text.split("\\s+");
            	for(int k=0;k<IDandName.length;k+=2) {
            		int ID=Integer.parseInt(IDandName[k]);
            		String name=IDandName[k+1];
            		students.addID(ID);
            		students.addName(name);
            	}
            }
        }
        //題目最大編號
        int questionmaxnumber=0;
        for(int j=0;j<n1;j++) {
        	Pattern pattern = Pattern.compile("#N:\\s*(\\d+).*");
        	Matcher matcher = pattern.matcher(str1.get(j));
        	if(matcher.find()){
        		int number =Integer.parseInt(matcher.group(1).trim());
        		if(questionmaxnumber<number) {
        			questionmaxnumber=number;
        		}
        	}
        }
        //題目資訊
        Question []questions=new Question[questionmaxnumber];
        for(int j=0;j<n1;j++) {
        	Pattern pattern = Pattern.compile("#N:\\s*(\\d+)\\s*#Q:\\s*(.*?)\\s*#A:\\s*(.*)\\s*");
            Matcher matcher = pattern.matcher(str1.get(j));
            if(matcher.find()){
                int number =Integer.parseInt(matcher.group(1).trim());
                String content=matcher.group(2).trim();
                String standarAnswer=matcher.group(3).trim();
                questions[number-1]=new Question(number,content,standarAnswer);
            }
        }
        //刪除題目
        for(int j=0;j<n5;j++) {
        	Pattern pattern = Pattern.compile("#D:N-(\\d+)");
            Matcher matcher = pattern.matcher(str5.get(j));
            if(matcher.find()){
            	int number =Integer.parseInt(matcher.group(1).trim());
            	questions[number-1].setDelect(number);
            }
        }
        //試卷資訊
        int maxPaperNumber=0;
        for(int j=0;j<n2;j++){
            Pattern pattern = Pattern.compile("#T:(\\d+)\\s+(.*)");
            Matcher matcher = pattern.matcher(str2.get(j));
            if(matcher.find()){
                int testnumber=Integer.parseInt(matcher.group(1).trim());
                if(testnumber>maxPaperNumber){
                    maxPaperNumber=testnumber;
                }
            }
        }
        Paper []testPaper=new Paper[maxPaperNumber];
        for(int j=0;j<maxPaperNumber;j++){
            testPaper[j]=new Paper(); 
        }
        for(int j=0;j<n2;j++) {
        	Pattern pattern = Pattern.compile("#T:(\\d+)\\s+(.*)");
            Matcher matcher = pattern.matcher(str2.get(j));
            if(matcher.find()){
            	int testnumber=Integer.parseInt(matcher.group(1).trim());
            	testPaper[testnumber-1].setNumber(testnumber); 
                if(matcher.group(2).equals("")){
                    continue;
                }
            	String text=matcher.group(2);
            	text=text.replaceAll("-", " ");
            	text=text.trim();
            	String []questionNumberAndScore=text.split("\\s+");
            	for(int k=0;k<questionNumberAndScore.length;k+=2) {
            		int questionNumber=Integer.parseInt(questionNumberAndScore[k].trim());
            		int score=Integer.parseInt(questionNumberAndScore[k+1].trim());
            		testPaper[testnumber-1].addQuestoinScores(score);
            		if(questionNumber>questionmaxnumber) {
            			testPaper[testnumber-1].addQuestions(null);
            		}
            		else {
            			testPaper[testnumber-1].addQuestions(questions[questionNumber-1]);
            		}            		
            	}
            }
        }
        //試卷答題資訊        
        int maxNumberStudentAnswer=0;
        for(int j=0;j<n4;j++) {
        	Pattern pattern = Pattern.compile("#S:\\s*(\\d+)\\s+(\\d+)\\s*(.*)");
            Matcher matcher = pattern.matcher(str4.get(j));
            if(matcher.find()){
            	int papernumber=Integer.parseInt(matcher.group(1).trim());
            	if(papernumber>maxNumberStudentAnswer) {
            		maxNumberStudentAnswer=papernumber;
            	}
            }
        }
        PaperAnswer []paperAnswer=new PaperAnswer[maxNumberStudentAnswer];
        for(int j=0;j<maxNumberStudentAnswer;j++) {
        	paperAnswer[j]=new PaperAnswer();
        }
        int []array=new int[maxNumberStudentAnswer];
        StudentAnswer []studentAnswer=new StudentAnswer[n4];
        for(int j=0;j<n4;j++) {
        	studentAnswer[j]=new StudentAnswer();
        	Pattern pattern = Pattern.compile("#S:\\s*(\\d+)\\s+(\\d+)\\s*(.*)");
            Matcher matcher = pattern.matcher(str4.get(j));
            
            if(matcher.find()){
            	int papernumber=Integer.parseInt(matcher.group(1).trim());
                array[papernumber-1]++;
            	paperAnswer[papernumber-1].setNumber(papernumber);
            	for(int k=0;k<maxPaperNumber;k++) {
            		if(papernumber==testPaper[k].getNumber()) {
            			paperAnswer[papernumber-1].setTest(testPaper[k]);
            		}
            	}
            	
            	int ID=Integer.parseInt(matcher.group(2).trim());
            	studentAnswer[j].setStudentID(ID);
            	String text1=matcher.group(3);//對答案匹配
            	String []text2=text1.split("#A:");
            	for(int k=0;k<text2.length;k++) {
            		if(text2[k].equals("")) {
            			continue;
            		}
            		String []word=text2[k].trim().split("-");
            		int number=Integer.parseInt(word[0].trim());
                    String answer;
                    if(word.length==2){
                        answer=word[1];
                    }
            		else{
                        answer="";
                    }
            		studentAnswer[j].addQuestionsNumber(number);
            		studentAnswer[j].addQuestionsAnswer(answer);            		                       
            	}
            	paperAnswer[papernumber-1].addStudentsAnswer(studentAnswer[j]); 
            }
        }
        View view=new View();
        for(int j=0;j<maxPaperNumber;j++) {
            if(testPaper[j].getNumber()!=0){
                view.scoreWarnning(testPaper[j]);
            }
        }
        for(int j=0;j<maxNumberStudentAnswer;j++){
            if(array[j]!=0){
                view.answerInformation(paperAnswer[j], students);
            }
        }
	}   
}

類圖:

分析:設計6個類,學生類,問題類,試卷類,學生答卷類,答卷類,輸出類。有5種資訊,先用正規表示式對每行字串進行匹配分類,都不匹配則輸出警告。再依次對字串拆分,儲存到題目試卷答卷學生中。把題目儲存到試卷中,試卷儲存到答卷中,答案儲存到學生答卷中,學生答卷再儲存到答卷中。最後進行判題並依次輸出。

3.採坑心得

1.審題:看清楚題目要求,對與輸入格式要仔細看,看清楚具體的格式才能更好的使用正規表示式去比配拆分等等,看懂答案輸出順序是怎樣的
2.對於邊界要分清楚,不然經常會非零返回
3.對於類設計結構要清晰,不然整體思路會錯,在後面再改可能和重新寫一樣
4.對於answe is null的輸出,應該是與題目的順序一致(一開始在最後一起輸出,一直沒發現有錯)

4.改進建議
1.對於類的職責要劃分清楚,要遵守單一職責,不能全在主類中寫
2.對於每一種功能的實現,應該建立一個類來履行這些職責
3.對於非零返回,應該仔細檢查程式碼中是否有越界或讀到了空
4.對類的設計應該更加具體明確

5.總結

這三次的作業總體來說較難,題目量雖然也不多,但是有些題目還是需要靜下心來思考怎麼去實現,要用心設計類,想好每個類應該有哪些功能。
這幾次作業讓我發現了自己一個問題,不會去思考哪些功能可以設計成類,喜歡把東西都放在主類中寫。我感覺到沒有完全掌握類的設計,應該多去思考怎麼做類設計。

相關文章