OOP題目集1~3的總結

^En發表於2024-04-19

目錄

(一)前言

(二)作業介紹

(三)演算法與程式碼

(四)SourceMonitor程式碼分析

(五)自學內容

(六)總結


一、前言

介紹本篇部落格的大致內容、寫作目的、意義等

本篇部落格介紹如何使用Java語言基礎和演算法來解決題目問題,在此基礎上進行對最近Java程式語言學習的總結

題目的難度為Java入門,主要考察類的設計與建立物件的使用陣列的基本使用關聯類結構設計等一些基礎演算法以及一些自學內容


二、作業介紹

展示作業題目,並梳理演算法思路

題目內容

前三次PTA作業共12大題,本篇部落格將挑選其中幾道典型題目進行舉例與分析,題目分別考查了:

類的設計與建立,題目(1)如圖:

類陣列的基本使用,題目(2)如圖:

陣列的排序與查詢,題目(3)如圖:

等一些基礎題型,以及空間結構較複雜的題型——包含多個知識點,題目(4)如圖:

答題判題程式 題目組共有三題,其中,上圖的 * 答題判題程式-3* 是對 答題判題程式-1答題判題程式-2 的增補和迭代。因此,下面內容將以本題為側重點展開分析與總結,其他基礎題將簡略帶過


三、演算法與程式碼

展示個人解決題目的演算法思路以及答案

演算法大綱

題目(1):

本題需要建立:

  • 風扇類class Fan,包含:
    • 三個速度等級常量—SlOW=1、MEDIUM=2、FAST=3
    • 整型—speed(速度)
    • 布林型—on(開關:true=開/false=關)
    • 雙精度浮點型—radius(半徑)
    • 字串型—color(顏色)

用順序結構進行處理,修改輸出格式後即可


題目(2):

本體需要建立:

  • 學生類class Student,包含:
    • 字串型—num(學號)
    • 字串型—name(姓名)
    • 雙精度浮點型—chinese(語文成績)
    • 雙精度浮點型—math(數學成績)
    • 雙精度浮點型—physic(物理成績)
    • 方法—getsum()(計算總分)
    • 方法—getaverage()(計算平均分)
    • 方法—printscore()(按格式輸出)
  • 類陣列s[ ]——存放學生資訊資料

用迴圈結構收集輸入資訊,按輸出格式後即可

題目(3):

本題需要建立:

  • 手機類class MobilePhone,包含:
    • 字串型—type(型號)
    • 整型—price(價格)
  • 比較器介面class Comparable,分析價格大小,返回對應關係
  • 陣列列表List[MobilePhone] list——存放手機資訊資料

用迴圈結構收集輸入資訊,遍歷初始List,遍歷使用比較器後的List,迴圈順序查詢手機後輸出即可


題目(4):

Tips

1、題目輸入按照一定格式規律,因此可以運用正規表示式來高效處理輸入資料,且處理輸入時運用while( input.hasNextLine() ){ }迴圈,逐行收集輸入資訊,知道該行字串為end時退出迴圈


2、在審閱題目(下兩圖)時,可以發現試卷資訊答卷資訊格式較其他輸入不同,多個【題目】—【分值】/【答題順序】-【答案】共用一個【試卷編號】/【答卷編號】,即輸入資訊有階級關係,因此需要在試卷類答卷類中額外建立一個集合來存放和引用輸入資訊。而集合(Linked)Hashmap的特點適合這種格式,因此將會使用 HashmapLinkedHashMap相關特點自學內容中)


3、題目輸出的錯誤提示較多且有優先順序順序輸出,所以做題之前應做好輸出提示的優先順序排序,優先順序越高的程式碼塊 應越靠前/在越外層的迴圈

本題需要建立:

  • 題目類class Question,包含:

    • 整型—num(題目編號)

    • 字串型—content(題目內容)

    • 字串型—standardanswer(標準答案)

    • 整型—score(題目分值)

    • 整型—flag(是否被刪除:true=已被刪除/false=未被刪除)

    • 方法—Right_Result()(答題正確輸出)

    • 方法—Wrong_Result( String wrong_answer )(答題錯誤輸出)

  • 試卷類class Exam_paper,包含:

    • 整型—paper_num(試卷編號)
    • 連結串列LinkedHashMap<Integer,Integer> score_map——存放試卷中的題目及對應分值
    • 方法—put_score_map(int num, int score )(score_map新增新元素)
    • 方法—Check_total_score()(檢測當前試卷是否滿分為100分)
  • 學生類class Student,包含:

    • 字串型—ID(學號)
    • 字串型—name(姓名)
  • 答卷類class Answer,包含:

    • 整型—paper_num(答卷編號)
    • 字串型—ID(學號)
    • 連結串列LinkedHashMap<Integer,String> answer_map——存放答卷中的答題順序及對應答案
    • 方法—put_answer_map(int order, String answer )(answer_map新增新元素)
  • 刪除題目類class Delete,包含:

    • 整型—delete_num(刪除題目編號)

主函式

  • 陣列列表List[Question] questionArrayList——存放 題目類 資訊
  • 陣列列表List[Exam_paper] exam_paperArrayList——存放 試卷類 資訊
  • 陣列列表List[Student] studentsArrayList——存放 學生類 資訊
  • 陣列列表List[Answer] answerArrayList——存放 答卷類 資訊
  • 陣列列表List[Delete] deleteArrayList——存放 刪除題目類 資訊
  • 連結串列LinkedList score——臨時記錄當前答卷人的各題賦分情況

本題的演算法有不同種,這裡只提供我的個人思路:

​ 採用迴圈結構利用正規表示式逐行分析輸入——>判斷試卷分值——>記錄刪除的題目——>試卷賦分——>核對試卷與答卷編號——>按照試卷順序去答卷中查詢試卷題號——>判斷題目是否被刪除——>判斷答題是否正確並記錄得分——>判斷是否有題目漏答——>查詢學生資訊——>輸出學生答題得分


程式碼

題目(1):

import java.util.Scanner;
class Fan
{
    public final int slow=1;
    public final int medium=2;
    public final int fast=3;
    private int speed=1;
    private boolean on=false;
    private double radius=5;
    private String color="white";

    Fan(int Speed, boolean On, double Radius, String Color)
    {
        this.speed=Speed;
        this.on=On;
        this.radius=Radius;
        this.color=Color;
    }

    public String toString()
    {
        String s="speed "+speed+"\n";
        s+="color "+color+"\n";
        s+="radius "+radius+"\n";
        if(on)
        {
            s+="fan is on";
        }
        else
        {
            s+="fan is off";
        }

        return s;
    }
}

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

        System.out.println("-------");
        System.out.println("Default");
        System.out.println("-------");

        Fan f1=new Fan(1,false,5,"white");

        System.out.println( f1.toString() );

        System.out.println("-------");
        System.out.println("My Fan");
        System.out.println("-------");

        int f2_speed=input.nextInt();
        boolean f2_on=input.nextBoolean();
        double f2_radius=input.nextDouble();
        String f2_color=input.next();

        Fan f2=new Fan( f2_speed,f2_on,f2_radius,f2_color );

        System.out.println( f2.toString() );
    }
}

題目(2):

import java.util.Scanner;
class Student
{
    private String num;
    private String name;
    private double chinese;
    private double math;
    private double physic;

    Student(String num, String name,double chinese, double math,double physic)
    {
        this.num=num;
        this.name=name;
        this.chinese=chinese;
        this.math=math;
        this.physic=physic;
    }
    public  int getsum()
    {
        return (int)( chinese + math + physic );
    }

    public  double getaverage()
    {
        return ( chinese + math + physic ) / 3;
    }

    public String printscore()
    {
        //format四捨五入保留兩位小數
        String average = String.format( "%.2f", getaverage() );
        
        return num + " " + name + " " + getsum() + " " + average;
    }
}

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

        Student[] s = new Student[5];

        for(int i=0;i<5;i++)
        {
            String num = input.next();
            String name = input.next();
            double chinese = input.nextDouble();
            double math = input.nextDouble();
            double physics = input.nextDouble();

            s[i]=new Student(num,name,chinese,math,physics);
        }

        for(int i=0;i<5;i++)
        {
            System.out.println( s[i].printscore() );
        }
    }
}

題目(3):

import java.util.*;
class MobilePhone
{
    public String type;
    public int price;
    public MobilePhone(String type, int price)
    {
        this.type = type;
        this.price = price;
    }

    //主動呼叫 toString 庫函式,用toString函式產生的字串來輸出
    public String toString()
    {
        return "型號:" + type + ",價格:" + price;
    }
}

class Comparable implements Comparator<MobilePhone>
{
    public int compare(MobilePhone phone1 , MobilePhone phone2 )
    {
        if( phone1.price > phone2.price )
            return 2;
        else if( phone1.price == phone2.price )
            return 0;
        else return -1;
    }
}

class Main
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        List<MobilePhone> list = new ArrayList<>();
        //依次輸入
        for( int i = 0 ; i<3 ; i++ )
        {
            MobilePhone mobilePhone = new MobilePhone( input.next()  , input.nextInt() );
            list.add( mobilePhone );
        }

        String inputString = input.next();
        int inputInteger = input.nextInt();
        MobilePhone search = new MobilePhone( inputString , inputInteger );

        //遍歷原始list
        System.out.println( "排序前,連結串列中的資料:" );
        for ( MobilePhone mobilePhone:list )
        {
            System.out.println( mobilePhone );
        }

        Comparable comparable = new Comparable();

        list.sort( comparable );

        //遍歷排序list
        System.out.println( "排序後,連結串列中的資料:" );
        for ( MobilePhone mobilePhone:list )
        {
            System.out.println( mobilePhone );
        }

        //查詢輸入手機
        for( MobilePhone mobilePhone : list )
        {
            if( mobilePhone.price == search.price )
            {
                System.out.print( search.type + "與連結串列中的" + mobilePhone.type + "價格相同");
                return;
            }
        }
        System.out.print("連結串列中的物件,沒有一個與" + search.type + "價格相同的");
    }

}

題目(4):

import java.util.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//1、題目資訊  "#N:"+題目編號+" "+"#Q:"+題目內容+" "#A:"+標準答案
class Question
{
    int num;
    String content;
    String standardanswer;
    int score;
    int flag=1;
    public Question(int num,String content,String standaanswer)
    {
        this.num = num;
        this.content = content;
        this.standardanswer = standaanswer;
    }

    //主動呼叫 toString 庫函式,用toString函式產生的字串來輸出
    public String toString()
    {
        return num+" "+content+" "+standardanswer+" "+score+" "+flag;
    }

    public void Right_Result()
    {
        System.out.println(content+"~"+standardanswer+"~true");
    }

    public void Wrong_Result( String wrong_answer )
    {
        System.out.println(content+"~"+wrong_answer+"~false");
    }
}

//2、試卷資訊  "#T:"+試卷號+" "+題目編號+"-"+題目分值
class Exam_paper
{
    int paper_num;
    LinkedHashMap<Integer,Integer> score_map = new LinkedHashMap<>();
    public void put_score_map(int num, int score )
    {
        score_map.put( num , score );
    }
    public Exam_paper(int paper_num)
    {
        this.paper_num=paper_num;
    }
    public void Check_total_score()
    {
        int total_score=0;
        // 迭代值
        for (Integer score : score_map.values())
        {
            total_score=total_score+score;
        }
        if(total_score!=100)
        {
            System.out.println( "alert: full score of test paper"+ paper_num +" is not 100 points" );
        }
    }
    public String toString()
    {
        return paper_num+" "+score_map;
    }
}

//3、學生資訊  "#X:"+學號+" "+姓名+"-"+學號+" "+姓名....+"-"+學號+" "+姓名
class Student
{
    String ID;
    String name;
    public Student(String ID,String name)
    {
        this.ID=ID;
        this.name=name;
    }

    public String toString()
    {
        return ID+" "+name;
    }
}


//4、答卷資訊  **"#S:"+試卷號+" "+"#A:"+答案內容**
class Answer
{
    int paper_num;
    String ID;
    LinkedHashMap<Integer,String> answer_map = new LinkedHashMap<>();
    public Answer(int paper_num,String ID)
    {
        this.paper_num=paper_num;
        this.ID=ID;
    }
    public void put_answer_map(int order, String answer )
    {
        answer_map.put( order,answer );
    }

    public String toString()
    {
        return paper_num+" "+ID+" "+answer_map;
    }
}

class Delete
{
    int delete_num;
    public Delete(int delete_num)
    {
        this.delete_num=delete_num;
    }
    public String toString()
    {
        return String.valueOf(delete_num);
    }
}

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

        String regex_Question = "#N:\\s*(\\d+)\\s*#Q:(.+) #A:(.+)";
        Pattern pattern_Question = Pattern.compile(regex_Question);

        String regex_Exam_paper = "#T:\\s*(\\d+)(\\s*\\d+-\\d+)*\\s*";
        Pattern pattern_Exam_paper = Pattern.compile(regex_Exam_paper);

        String regex_Student = "#X:(-*\\s*\\d+\\s+.*\\s*)*";
        Pattern pattern_Student = Pattern.compile(regex_Student);

        String regex_Answer = "#S:\\s*(\\d*)\\s*(\\d*)(\\s*#A:\\d+-[^#]*)*";
        Pattern pattern_Answer = Pattern.compile(regex_Answer);

        String regex_Delete = "^#D:\\s*N\\s*-\\s*(\\d+)\\s*$";
        Pattern pattern_Delete = Pattern.compile(regex_Delete);

        List<Question> questionArrayList = new ArrayList<>();
        List<Exam_paper> exam_paperArrayList = new ArrayList<>();
        List<Student> studentsArrayList = new ArrayList<>();
        List<Answer> answerArrayList = new ArrayList<>();
        List<Delete> deleteArrayList = new ArrayList<>();

        //輸入
        while( input.hasNextLine() )
        {
            //當前一行的輸入字串
            String inputString = input.nextLine();

            Matcher pmatcher_Question = pattern_Question.matcher(inputString);
            Matcher pmatcher_Exam_paper = pattern_Exam_paper.matcher(inputString);
            Matcher pmatcher_Student = pattern_Student.matcher(inputString);
            Matcher pmatcher_Answer = pattern_Answer.matcher(inputString);
            Matcher pmatcher_Delete = pattern_Delete.matcher(inputString);

            //輸入字串是end,則輸入完畢退出迴圈
            if(inputString.equals("end"))
                break;

                //inputString==輸入1、題目資訊  "#N:"+題目編號+" "+"#Q:"+題目內容+" "#A:"+標準答案
            else if(pmatcher_Question.matches())
            {
                Question question = new Question(Integer.parseInt(pmatcher_Question.group(1).trim()), pmatcher_Question.group(2).trim(), pmatcher_Question.group(3).trim());
                questionArrayList.add(question);
            }

            //inputString==輸入2、試卷資訊  "#T:"+試卷號+" "+題目編號+"-"+題目分值
            else if(pmatcher_Exam_paper.matches())
            {
                //試卷編號
                Exam_paper exam_paper = new Exam_paper( Integer.parseInt( pmatcher_Exam_paper.group(1).trim() ) );

                Pattern pattern = Pattern.compile("(\\d+)\\s*-\\s*(\\d*)");
                Matcher patternmatcher = pattern.matcher(inputString);

                while ( patternmatcher.find() )  //區域性匹配,呼叫第二次會繼續向下匹配
                {
                    //Map<題目編號-分值>
                    exam_paper.put_score_map( Integer.parseInt( patternmatcher.group(1).trim() ) , Integer.parseInt( patternmatcher.group(2) ) );
                }
                exam_paperArrayList.add(exam_paper);
            }

            //inputString==3、學生資訊   "#X:"+學號+" "+姓名+"-"+學號+" "+姓名....+"-"+學號+" "+姓名
            else if( pmatcher_Student.matches() )
            {
                Pattern pattern = Pattern.compile("(\\d+)\\s+([^-]+)");
                Matcher patternmatcher = pattern.matcher(inputString);

                while ( patternmatcher.find() )
                {
                    //學號-姓名
                    Student student = new Student( patternmatcher.group(1).trim(),patternmatcher.group(2).trim() );
                    studentsArrayList.add(student);
                }
            }

            //inputString==4、答卷資訊  "#S:"+試卷號+" "+學號+"#A:"+試卷題目的順序號+"-"+**+答案內容+...
            else if(pmatcher_Answer.find())
            {
                //試卷編號-學號
                Answer answer = new Answer( Integer.parseInt(pmatcher_Answer.group(1)),pmatcher_Answer.group(2));

                Pattern pattern = Pattern.compile("#A:\\s*(\\d+)-([^#|\\n]*)");
                Matcher patternmatcher = pattern.matcher(inputString);

                while ( patternmatcher.find() ) //區域性匹配,呼叫第二次會繼續向下匹配
                {
                    answer.put_answer_map( Integer.parseInt(patternmatcher.group(1).trim()),patternmatcher.group(2).trim() );
                }
                answerArrayList.add(answer);
            }

            //inputString==5、刪除題目資訊  "#D:N-"+題目號
            else if(pmatcher_Delete.matches())
            {
                Delete delete = new Delete( Integer.parseInt(pmatcher_Delete.group(1).trim()) );
                deleteArrayList.add(delete);
            }

            //輸入資訊只要不符合格式要求,均輸出”wrong format:”+資訊內容       例如:wrong format:2 #Q:2+2=
            else
            {
                System.out.println("wrong format:"+inputString);
            }

        }//總while結束


        //判斷試卷分值是否100
        for( int i=0;i<exam_paperArrayList.size();i++ )
        {
            exam_paperArrayList.get(i).Check_total_score();
        }

        if( exam_paperArrayList.size()==0 )
        {
            Exam_paper exam_paper = new Exam_paper( 0 );
            exam_paper.put_score_map( 0 , 0 );
            exam_paperArrayList.add(exam_paper);
        }

        //刪除題目並記錄
        for( int i=0;i<deleteArrayList.size();i++ )
        {
            int num=deleteArrayList.get(i).delete_num;
            //選中刪除題目,修改flag
            for(int j=0;j< questionArrayList.size();j++)
            {
                if( questionArrayList.get(j).num==num )
                {
                    questionArrayList.get(j).flag=0;
                }
            }
        }


        for( int S=0;S<answerArrayList.size();S++ )  //幾份答卷
        {
            boolean flag=false;
            for( int T=0;T<exam_paperArrayList.size();T++ )
            {
                if( answerArrayList.get(S).paper_num == exam_paperArrayList.get(T).paper_num )
                {
                    flag=true;
                }
            }

            for( int T=0;T<exam_paperArrayList.size();T++ )  //幾份試卷分則
            {
                //判斷試卷編號是否相同
                if( flag )
                {
                    //當前試卷題目賦分值
                    for( Integer num: exam_paperArrayList.get(T).score_map.keySet() )  //當前試卷分則有幾份分值
                    {
                        //根據#T 搜尋題號
                        Optional<Question> questionOptional = questionArrayList.stream().filter(question -> num == (question.num)).findFirst();

                        //搜到了題號
                        if( !questionOptional.isEmpty() )
                        {
                            questionOptional.get().score=exam_paperArrayList.get(T).score_map.get(num);
                        }
                    }
                    
                    //記錄分數
                    LinkedList<Integer> score = new LinkedList<>();
                    //檢測#A
                    int t=1;//#T裡的第幾個
                    Cycle:for( Integer current_num: exam_paperArrayList.get(T).score_map.keySet() )
                    {
                        //迴圈查詢題目
                        for( Integer current_order: answerArrayList.get(S).answer_map.keySet() )
                        {
                            if (current_order == t)
                            {
                                //搜尋當前題號current_num資訊
                                int finalCurrent_num = current_num;
                                Optional<Question> questionOptional = questionArrayList.stream().filter(question -> finalCurrent_num == (question.num)).findFirst();

                                //找到current_num題目
                                if (!questionOptional.isEmpty())
                                {
                                    //題目有效
                                    if (questionOptional.get().flag == 1)
                                    {
                                        //判斷是否答對  計算分數
                                        if (answerArrayList.get(S).answer_map.get(current_order).equals(questionOptional.get().standardanswer))
                                        {
                                            questionOptional.get().Right_Result();
                                            score.add(questionOptional.get().score);

                                            t++;
                                            continue Cycle;
                                        }
                                        else
                                        {
                                            questionOptional.get().Wrong_Result(answerArrayList.get(S).answer_map.get(current_order));
                                            score.add(0);

                                            t++;
                                            continue Cycle;
                                        }
                                    }
                                    //#S:裡的#A:答了刪除的題目                                    the question 2 invalid
                                    else if (questionOptional.get().flag == 0)
                                    {
                                        System.out.println("the question " + current_num + " invalid~0");
                                        score.add(0);
                                    }
                                }
                                //沒找到
                                else
                                {
                                    System.out.println("non-existent question~0");
                                    score.add(0);
                                    t++;

                                    continue Cycle;
                                }
                            }
                        }

                        t++;

                    }//輸入的#A檢測完


                    //#S:裡的#A: < #T裡的個數  輸入的答案資訊少於試卷的題目數量        answer is null
                    if( answerArrayList.get(S).answer_map.size() < exam_paperArrayList.get(T).score_map.size() )
                    {
                        int count=exam_paperArrayList.get(T).score_map.size()-answerArrayList.get(S).answer_map.size();
                        while( count>0 )
                        {
                            System.out.println("answer is null");
                            score.add(0);
                            count--;
                        }
                    }


                    //搜尋學生
                    int finalS = S;
                    Optional<Student> studentOptional = studentsArrayList.stream().filter(student -> answerArrayList.get(finalS).ID.equals(student.ID)).findFirst();

                    //#S:裡的學號在#X:裡沒有  學號引用錯誤                          20201103 not found
                    if( studentOptional.isEmpty() )
                    {
                        System.out.println(answerArrayList.get(S).ID+" not found");
                    }
                    else
                    {
                        System.out.print(studentOptional.get().ID+" "+studentOptional.get().name+": ");

                        //輸出分數
                        int total_score=0;
                        if(score.size()==0 )
                        {
                            System.out.print("0");
                        }
                        for( int k=0;k<score.size();k++ )
                        {
                            total_score=total_score+score.get(k);
                            System.out.print( score.get(k) );
                            if( k!= score.size()-1 )
                            {
                                System.out.print(" ");
                            }
                            else
                            {
                                System.out.println("~"+total_score);
                            }
                        }
                    }

                }
                //#S:裡的paper_num和#T:裡的papernum不等  試卷號引用錯誤         The test paper number does not exist
                else
                {
                    System.out.println("The test paper number does not exist");
                }
                break;
            }
        }
    }
}

可以看到最後一題的演算法複雜度高,且又因為我是Java初學者,故需要自學一些內容,下面將進行個人對自學內容一些重點的整理


四、SourceMonitor程式碼分析

題目(1):

題目(2):

題目(3):

題目(4):


五、自學內容

展示自學內容,並進行重點的歸納和整理(這裡只展示個人認為比較重要且題目需要用到的知識點)

正規表示式

推薦正規表示式的網上測試工具網址:<正規表示式線上測試 | 菜鳥工具 (jyshare.com)>裡面附帶下圖最基本的正規表示式語法參考


Pattern類Matcher 方法

(1) Matcher 匹配器類,透過 Pattern 執行匹配操作,基本用法為:

Pattern [pattern名稱] = Pattern.compile([正規表示式/固定字串]);
Matcher [matcher名稱] = [pattern名稱].matcher([被匹配的字串]);

(2).matches() 方法:對整個字串進行匹配,匹配成功返回true

例:正規表示式:\d+ //至少一個數字

​ 被匹配字串:12345 //匹配成功

​ 被匹配字串:12345abc //匹配失敗

//(1)程式碼
if( [matcher名稱].matches() ){
	System.out.println("匹配成功");
}

(3).find() 方法:對字串進行區域性匹配,匹配成功返回true

.find()方法在匹配後會從匹配部分的下個位置開始

例:正規表示式:\d+ //至少一個數字

​ 被匹配字串:123abc //匹配成功一次

​ 被匹配字串:123abc123 //匹配成功兩次

//(1)程式碼
if( [matches名稱].find() ){
    System.out.println("匹配成功");
}

(4).group() 方法:透過對括號內的字元分組,對每個組進行處理的方法

group( [組數] ),括號中的整型(>0) 對應 正規表示式中按括號分組的區域性字元段;整型(=0)對應整個字串

Pattern pattern = Pattern.compile("(\\w+)-(\\d+)");  	//[至少一個數字]-[至少一個字母]
Matcher matcher = pattern.matcher("a-1,b-b,c-3,d-d");
while ( matcher.find() )  	//迴圈區域性匹配
{
    System.out.println("整組:" + matcher.group(0));
    System.out.println("組1:" + matcher.group(1));
    System.out.println("組2:" + matcher.group(2));
}

輸出如圖:

ArrayListLinkedList

需要匯入 java.util.Array 、java.util.LinkedList 包

異同

相同處:沒有固定大小的限制,可以新增或刪除元素

不同處:1)ArrayList按線性的順序儲存資料;LinkedList是在每一個節點裡存到下個節點地址的線性表

​ 2)ArrayList適用頻繁訪問列表中的某個元素,查詢和修改操作效率較低

​ LinkedList需要透過迴圈迭代來訪問列表中的元素,增加和刪除操作效率較高

(1)建立

ArrayList<E> [表名稱] =new ArrayList<>();  	//E—>泛型

LinkedList<E> [表名稱] = new LinkedList<E>();  	//E—>泛型,普通建立
LinkedList<E> [表名稱] = new LinkedList(Collection<? extends E> c); 	 //E—>泛型,集合建立

(2).add() 方法:新增元素

List.add( [元素] );  	//尾插一個新元素

(3). get() 方法:訪問元素

List.get( n-1 );  	//訪問第n個元素

(4)size() 方法:計算大小

List.size();  	//返回整型=表的元素個數

(5)for each 方法:迭代遍歷

for ( [元素型別] [迴圈變數] : [表名稱] ) 
{
    System.out.println([迴圈變數]);
}

HashMapLinkedHashMap

需要匯入 java.util.HashMap 、java.util.LinkedHashMap 包

異同

相同處:沒有固定大小的限制的雜湊表,它儲存的內容是鍵值對(key-value)對映

不同處:1)HashMap每次新增元素的存放位置是無序的;LinkedHashMap保證迭代順序,即按 照儲存順序排列

​ 2) LinkedHashMap額外加了 頭節點header標誌位accessOrder 兩個成員變數

(1)建立

HashMap<[key型別], [value型別]> [表名稱] = new HashMap<{[key型別], [value型別]}>();  	//E—>泛型,{}中內容可以省略

LinkedHashMap<[key型別], [value型別]> [表名稱] = new LinkedHashMap<{[key型別], [value型別]}>();  	//E—>泛型,{}中內容可以省略

(2).put() 方法:新增元素

Map.put( [key],[value] );  	//尾插一個新元素

(3). get(key) 方法:訪問鍵值對應對映值

Map.get( [key] );  	//訪問key的value

(4)size() 方法:計算大小

Map.size();  	//返回整型=表的元素個數

(5)for each 方法:迭代遍歷

// 輸出 key 和 value
for ([key型別] key : [表名稱].keySet() )   	//.keySet()方法當前獲取鍵值
{
    System.out.println( "key: " + key + " value: " + [表名稱].get(key) );
}

Comparator 和 **Comparable **方法

需要匯入 java.util.Comparator 包

異同

相同處:可以對 集合Collections 進行排序

不同處:Comparator 可以有更多的排序方法

數值排序

class [方法名稱] implements Comparator<[排序物件型別]>
{
    public int compare( [排序元素1] , [排序元素2] )  	//Comparator介面的方法 int compare(object o1,object o2);
    {
        if([排序元素1]>[排序元素2]) return 1;
        else if([排序元素1]>[排序元素2])  return -1;
        else return 0;
    }
}

字串排序

class [方法名稱] implements Comparator<[排序物件型別]>
{
    public int compare( [排序元素1] , [排序元素2] )  	
    {
        return [排序元素1].compareTO( [排序元素2] );  	//.compareTo()方法用於字串之間的比較
    }
}

六、總結

答題技巧

1)、在面對像答題判題程式-3這種工程量大,情況案例多的題目時,應在正式敲程式碼前提前設計好類設計演算法思路,否則在過程需要更多的時間精力進行修改除錯,甚至還會出現大程式碼塊需要刪除重新設計的情況

2)、在完成答題判題程式-3題目時,因為有錯誤格式Wrong Format的情況,應該適當的降低輸入門檻,即設計的正規表示式應該儘可能地讓更多種輸入格式不會報錯,如:題目內容僅僅是數學題——>題目內容可以是由數字,字母,漢字組成答卷#S裡的#A格式必須是【答題順序】—【答案】——>可以為【答題順序】—【空】或全為空

心得體會

1)、除答題判題程式題目組外,其他題目相對較簡單,考察新手對Java程式語言的一些基礎且重要的知識點,例如類的設計和物件類的封裝性

2)、相對C語言,Java語言的單一職責原則體現得更為顯著,要培養將相同物件的不同自定義方法函式放進類中,而不是像C一樣透過更多的自定義函式來處理。因為Java中的存在,Java的程式碼量更大,空間複雜度更高,也隨著題目難度的上升,任務更重

3)、這次答題判題程式-3共有28個測試得分點,而樣例卻只給出10個,因此開發程式時,思維不能固化,要學會主動聯想特殊情況,如答卷的答案漏答,或答題的題目已被刪除等特殊情況也要納入程式碼的考慮範圍內,這樣才能增加程式碼的質量,適用範圍更廣

個人建議

​ PTA中既然測試點遠大於給出樣例,為了方便學生理解,測試點提示應該更加準確具體易懂,否則不停的除錯搞錯了方向也是徒勞無功



E N D

相關文章