SCAU comprehensive experiment Java source code annotation and keyword analysis program (with class diagram)

Posted by svgk01 on Fri, 14 Jan 2022 13:47:55 +0100

SCAU comprehensive experiment Java source code annotation and keyword analysis program (with class diagram)

Title:

Category: D comprehensive experiment

Keywords: class, object, encapsulation, aggregation, composition, inheritance, IO

Content requirements:

1, Experimental purpose

(1) Master the basic methods of object-oriented programming

(2) Writing applications in the Java language

2, Experiment content: write a Java application program to analyze a single java source program file and all Java source program files (including subdirectories) in a directory. The analysis contents include:

The number of Java source program files required for directory analysis.

The number of characters in the Java source program. When analyzing the directory, it is the sum of the number of characters in all source program files.

The number of comments in the Java source program file, that is, the total number of comments in the source program file, including single line comments and multi line comments. When analyzing a directory, it is the sum of all source program files in it.

The number of characters of comments in the Java source program file, that is, the sum of the number of characters of all comments in the source program file. When analyzing a directory, it is the sum of all source program files in it.

Keyword usage in Java source program files, that is, how many times each keyword in the source program file is used. When analyzing a directory, it is the sum of all source program files in it.

Specific requirements are as follows:

1. When the program runs, the menu shown in the following figure is displayed first:

2. Requirements for analysis directory or source program file

When selecting menu item 1, you are first asked to enter the directory name or Java source file name to be analyzed. If the entered directory or file name does not exist, the prompt does not exist; When the extension of the entered file name is not ". Java", it will be prompted that it is not a java source program file. If you enter a java source file name, analyze the source file. If you enter a directory name, analyze all source program files in the directory. The analysis results are stored in a text file, a data directory is established in the current directory, and the result file is placed in the data directory. Result file name when analyzing Directory: D_ Directory name_ Result.txt, for example: D_lang_Result.txt when analyzing source program files, result file name: F_ Source file name_ Result.txt,

For example: F_String.java_Result.txt format of contents in result file:

Line 1: analysis Directory: C: \ program files \ Java \ jdk1 8.0_ 31\src\java

Line 2: blank line

Line 3: number of Java source program files: 1866 (no such line when analyzing the file)

Line 4: total number of characters in the source program: 29022541

Line 5: total number of notes: 57349

Line 6: comment total characters: 17559371

Line 7: blank line

Line 8: keyword usage is as follows:

Line 9: [int = 27705] (output each keyword and the number of times it is used from line 9, one per line)

Note: at the end of the analysis, the analysis results are not displayed, and the results are stored in a text file. The following prompt is displayed: the directory analysis is completed, and the analysis results are stored in the file [data/D_util_Result.txt]! Or: the file analysis is completed, and the analysis results are stored in the file [data/F_String.java_Result.txt]! When keyword is output, it is sorted from the largest to the smallest by the number of times used. When the number of times is the same, it is sorted alphabetically.

//All keywords of Java language public static final String[] KEYWORDS = {"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for" , “goto”, “if”, “implements”, “import”, “instanceof”, “int”, “interface”, “long”, “native”, “new”, “package”, “private”, “protected”, “public”, “return”, “short”, “static”, “strictfp”, “super”, “switch”, “synchronized”, “this”, “throw”, “throws”, “transient”, “try”, “void”, “volatile”, “while” };

2. When viewing the existing analysis results and selecting menu item 2, first list the analyzed and stored results, as shown in the following figure:

That is, all analysis result files stored in the data directory are listed and a sequence number is given. After entering the serial number of the file to view, the contents of the file are displayed. For example, the following figure:

3, Experiment completion prompt

1. When analyzing the number of comments and the number of characters of comments, it is assumed that there is no problem of comment nesting. That is, there are no following conditions in the files and directories used for the test: / * * / / Note 1 / / Note 2 / * /*

*2. When analyzing the number of comments and characters of comments, it is assumed that there is no comment form in the string direct quantity, that is, there is no following situation: String s = "/ abcd /";

3. When analyzing keyword usage times, note that the number of keywords cannot be calculated in the following cases:

(1) Keywords appearing in comments, such as the following int cannot be counted / * * * int k=0*/

(2) Keywords in string literals, such as the following int, cannot count system out. println(“input a int: ”);

(3) Pay attention to whole word recognition. For example, int in println is not a keyword and cannot be counted.

4. If you use regular expressions for programming, in addition to the basic regular expressions, you can refer to the following two classes of Java: Java util. regex. Pattern java. util. regex. Matcher

Code: there are five classes and an interface

First class: Main class (Main function)

Function: main function, which can call other functions (see notes for details)

code:

package finalExam;

import java.io.*;
import java.util.Scanner;

public class Main {
    private static String addressList;//Path to store input

    public static String getAddressList() {
        return addressList;
    }

    public static void setAddressList(String addressList) {
        Main.addressList = addressList;
    }

    //Main function
    public static void main(String[] args) throws IOException {

        Scanner scanner = new Scanner(System.in);
        while (true) {//Cycle to exit
            menu();
            int choose = scanner.nextInt();
            switch (choose) {//choice
                case 1: {
                    System.out.println("Please enter:");
                    String str = scanner.next();
                    AnalyseDir analyseDir = new AnalyseDir(str);//Create analyseDir object
                    File f = new File(str);
                    if (str.contains(".java")) {
                        addressList = str;
                        analyseDir.programData();
                    } else if (!f.exists()) {
                        System.out.println("This directory or file name does not exist");
                    } else if (f.isDirectory()) {
                        addressList = str;
                        analyseDir.documentData();
                    } else System.out.println("no Java Source program file");
                    break;
                }
                case 2: {
                    ScanResult.menu2();
                    break;
                }
                case 0:
                    return;
            }
//            scanner.close();
        }
    }

    public static void menu() {//main interface
        System.out.println("-------MENU-------");
        System.out.println(" 1.Analysis directory or source program file");
        System.out.println(" 2.View existing analysis results");
        System.out.println(" 0.sign out");
        System.out.println("------------------");
        System.out.println("Please select:");
    }

}

The second class: AnalyseDir

Function: analyze the input path, and analyze the directory name and file name respectively

code:

package finalExam;

import java.io.*;
import java.util.List;
import java.util.Objects;

public class AnalyseDir extends Main implements CorrectRoad {

    static String sdir = "data";

    private String str;

    //Parametric structure
    public AnalyseDir(String str) {
        this.str = str;
    }

    //encapsulation
    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }


    public void programData() throws IOException {//Source program file

        try (
                FileReader fr = new FileReader(str);
                BufferedReader bfr = new BufferedReader(fr)//Read with buffer
        ) {
            int sum = 0;
            while (bfr.read() != -1) {//Count characters
                sum++;
            }

            //Process path
            int i = CorrectRoad.nameWhere(str);
            String str3 = str.substring(i + 1);
            String str2 = str.substring(0, i);
            i = CorrectRoad.nameWhere(str2);//Second/
            String str1 = str.substring(0, i+1);
            File fdir = new File(str1 + sdir);
            String last = "F_" + str3 + "_Result.txt";
            File fdir2 = new File(str1 + sdir + "/" + last);
            if (!fdir.isDirectory()) {
                fdir.mkdir();
                fdir2.createNewFile(); // create a new file
            } else if (!fdir2.exists()) {
                fdir2.createNewFile(); // create a new file
            }

            List list = TheKeyWord.makeMap(str);
            BufferedWriter bw = new BufferedWriter(new FileWriter(fdir2));//Write with buffer
            SearchAnnotation searchAnnotation = new SearchAnnotation(str);
            try {
                bw.write(
                        "------------------------------------------------------------------\n" +
                                "Analysis directory :" + str + "\n" +
                                "\n" +
                                "Total number of characters in the source program : " + sum + "\n" +
                                "Total number of notes : " + searchAnnotation.search(0) + "\n" +
                                "Total number of characters in comments : " + searchAnnotation.search(1) + "\n" +
                                "\n" +
                                "Keyword usage is as follows:\n");
                for (Object o : list) {
                    bw.write(
                            "[" + o + "] \n");
                }
                bw.write(
                        "------------------------------------------------------------------");
            } catch (Exception e) {
                e.printStackTrace();
            }

            bw.flush();

            System.out.println("End of file analysis, The analysis results are stored in the file[data/F_" + str3 + "_Result.txt]!");
        }
    }

    public void documentData() throws IOException {//catalogue

        int count = 0, sum1 = 0, sum2 = 0, sum3 = 0;//For accumulation
        File fdir0 = new File(str);
        for (int i = 0; i < Objects.requireNonNull(fdir0.list()).length; i++) {
            if (Objects.requireNonNull(fdir0.list())[i].contains(".java")) {
                String strAddress = str + "/" + Objects.requireNonNull(fdir0.list())[i];
                SearchAnnotation searchAnnotation = new SearchAnnotation(strAddress);

                try {
                    FileReader fr = new FileReader(strAddress);
                    BufferedReader br1 = new BufferedReader(fr);
                    while (br1.read() != -1) {//Count characters
                        sum3++;
                    }
                    sum1 += searchAnnotation.search(0);//Total number of notes
                    sum2 += searchAnnotation.search(1);//Total number of characters in comments
                } catch (Exception e) {
                    e.printStackTrace();
                }
                count++;
            }
        }

        //Process path
        int j = CorrectRoad.nameWhere(str);
        String str3 = str.substring(j + 1);
        String str1 = str.substring(0, j + 1);
        File fdir = new File(str1 + sdir);
        String last = "D_" + str3 + "_Result.txt";
        File fdir2 = new File(str1 + "/" + sdir + "/" + last);
        if (!fdir.isDirectory()) {
            fdir.mkdir();
            fdir2.createNewFile(); // create a new file
        } else if (!fdir2.exists()) {
            fdir2.createNewFile(); // create a new file
        }

        List list = TheKeyWord.makeMap(str);
        BufferedWriter bw = new BufferedWriter(new FileWriter(fdir2));//Write with buffer
        bw.write(
                "------------------------------------------------------------------\n" +
                        "Analysis directory : " + str + "\n" +
                        "\n" +
                        "Java Number of source program files: " + count + " \n" +
                        "Total number of characters in the source program : " + sum3 + "\n" +
                        "Total number of notes : " + sum1 + "\n" +
                        "Total number of characters in comments : " + sum2 + "\n" +
                        "\n" +
                        "Keyword usage is as follows:\n");
        for (Object o : list) {
            bw.write(
                    "[" + o + "] \n");
        }
        bw.write(
                "------------------------------------------------------------------");
        bw.flush();

        System.out.println("End of catalog analysis, The analysis results are stored in the file[data/D_" + str3 + "_Result.txt]!");
    }

}

The third class: ScanResult

Function: realize the function of option 2 in the main menu

code:

package finalExam;

import java.io.*;
import java.util.Objects;
import java.util.Scanner;

public class ScanResult extends Main implements CorrectRoad {

    public static void showResult(File f, int n) throws IOException {

        String str;
        try (//Read with buffer
             FileReader fr = new FileReader(f.getPath()+'/'+ Objects.requireNonNull(f.list())[n - 1]);
             BufferedReader bfr = new BufferedReader(fr)
        ) {
            while ((str = bfr.readLine()) != null) {//Output file content
                System.out.println(str);
            }
        }
    }

    public static void menu2() throws IOException {//View existing analysis results interface
        String str;
        String str0 = getAddressList();
        if(str0.contains(".java")){
            int i = CorrectRoad.nameWhere(str0);
            String str2 = str0.substring(0, i);
            i = CorrectRoad.nameWhere(str2);
            String str3 = str2.substring(0, i);
            str = str3 + "/data";
        }else{
            String str1 = str0.substring(0, CorrectRoad.nameWhere(str0));//Adjust to readable path
            str = str1 + "/data";
        }
        Scanner scanner = new Scanner(System.in);
        File f = new File(str);
        System.out.println("--------------------------------------------");
        for (int i = 1; i <= Objects.requireNonNull(f.list()).length && Objects.requireNonNull(f.list())[i - 1] != null; i++) {
            System.out.println("   " + i + " -- " + Objects.requireNonNull(f.list())[i - 1]);
        }
        System.out.println("--------------------------------------------");
        System.out.println("Enter the number of the file to view:");
        int choose2 = scanner.nextInt();
        showResult(f,choose2);
    }
}

The fourth class: SearchAnnotation

Here is the only code that refers to other big guys, because I can't knock it out after knocking for a long time.

Purpose: find comments

code:

package finalExam;

import java.io.*;
import java.util.ArrayList;

public class SearchAnnotation extends AnalyseDir {

    //Parametric structure
    public SearchAnnotation(String str) {
        super(str);
    }

    public int search(int n) throws Exception {
        ArrayList<String> ve = new ArrayList<>();
        try (//Read with buffer
                FileReader fr = new FileReader(super.getStr());
                BufferedReader bfr = new BufferedReader(fr)
        ) {

            String s;
            while ((s = bfr.readLine()) != null) {//Use the readLine method to read one line at a time
                ve.add(s);
            }
        }
        if (n == 0) return operateNote(ve)[0];
        else return operateNote(ve)[1];
    }

    public static int[] operateNote(ArrayList<String> list) throws IOException {

        String s;
        int countNote = 0;
        int charInNote = 0;
        for (int j = 0; j < list.size(); j++) {
            s = list.get(j);
            int note1 = s.indexOf("/*");
            int note2 = s.indexOf("//");
            int note3 = s.indexOf("*/");
            //int note4=s.indexOf("\"");
            String dm = "\"(.*)\"";//Double quotation mark
            String sm = "\'(.*)\'";//Single quotation mark

            if (note1 != -1 && note3 == -1) {//multiline comment 
                countNote++;
                String ttt = list.get(j);
                list.set(j, ttt.substring(0, note1));
                charInNote += s.substring(note1).length() + 1;//+1 is including line breaks

                s = list.get(++j);
                while ((note3 = s.indexOf("*/")) == -1) {
                    if ((note2 = s.indexOf("//")) != -1) {
                        countNote++;
                    }
                    list.remove(j);

                    charInNote += s.length() + 1;
                    if (j < list.size() - 1) {
                        s = list.get(++j);
                    } else {
                        break;
                    }
                }
                list.set(j, "");
                charInNote += s.length();

            } else if (note2 != -1) {// Single line comment for "/ /" class
                countNote++;
                list.set(j, s.substring(0, note2));
                charInNote += s.substring(note2).length() + 1;
            } else if (note1 != -1 && note3 != -1) {//Single-Line Comments 
                countNote++;

                String m1 = s.substring(0, note1);
                String m2 = s.substring(note3 + 2);
                String m3 = m1 + m2;
                charInNote += s.substring(note1, note3 + 2).length();
                list.set(j, m3);
            } else {//Delete output statement
                String rp = list.get(j);
                rp = rp.replaceAll(dm, "");
                list.set(j, rp);
            }
        }
        return new int[]{countNote, charInNote};
    }
}


The fifth class: TheKeyWord

Here is their own knock out, do not use regular expressions, just want to!

Function: find 50 java keywords

code:

package finalExam;

import java.io.*;
import java.util.*;

public class TheKeyWord extends AnalyseDir {

    public static final String[] KEYWORDS = {"abstract", "assert", "boolean", "break", "byte", "case",
            "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum",
            "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof",
            "int", "interface", "long", "native", "new", "package", "private", "protected", "public",
            "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw",
            "throws", "transient", "try", "void", "volatile", "while"};//50 key words

    //Parametric structure
    public TheKeyWord(String str) {
        super(str);
    }

    public static void check(Map<String, Integer>map, String str) throws IOException {
        try (
                FileReader fr = new FileReader(str);
                BufferedReader bfr = new BufferedReader(fr)
        ) {
            String s, s1;
            int is = 1;
            while ((s1 = bfr.readLine()) != null) {//Use the readLine method to read one line at a time
                //Comment on
                if (s1.contains("/**") && is == 1) {
                    is = 0;
                }else if(s1.contains("*/")){
                    is = 1;
                }else if(is == 0 && s1.contains("*")){
                }else if(is == 1) {
                    for (Map.Entry<String, Integer> entry : map.entrySet()) {
                        s = s1;
                        while (s.contains(entry.getKey())) {
                            //Pair compound words
                            if (((s.indexOf(entry.getKey()) != 0) && (s.charAt(s.indexOf(entry.getKey()) - 1) != ' ')) || ((s.indexOf(entry.getKey()) + entry.getKey().length() < s.length()) && ((s.charAt(s.indexOf(entry.getKey()) + entry.getKey().length()) != ' ')))) {
                                //Double quotation marks
                                if (s.indexOf('"') >= 0 && (s.indexOf('"') < s.indexOf(entry.getKey())) && ((s.substring(s.indexOf('"') + 1)).indexOf('"') > 0) && ((s.substring(s.indexOf('"') + 1)).indexOf('"') > s.indexOf(entry.getKey()))) {
                                    s = s.substring(s.indexOf('"') + 2 + ((s.substring(s.indexOf('"') + 1)).indexOf('"')));
                                    if (s.contains(entry.getKey())) entry.setValue(entry.getValue() + 1);
                                }

                            } else {
                                entry.setValue(entry.getValue() + 1);
                            }
                            if (s.contains(entry.getKey()) && is == 1) {
                                s = s.substring(s.indexOf(entry.getKey()) + entry.getKey().length());
                            }
                        }
                    }
                }
            }
        }
    }

    public static List makeMap(String str) throws IOException {

        Map<String, Integer> map = new HashMap<>();

        for (String keyword : KEYWORDS) {//Initialize keyword map
            map.put(keyword, 0);
        }

        if (str.contains(".java")) {
            check(map, str);
        } else {
            File fdir0 = new File(str);
            for (int i = 0; i < Objects.requireNonNull(fdir0.list()).length; i++) {//Traverse each file
                if (Objects.requireNonNull(fdir0.list())[i].contains(".java")) {
                    String strAddress = str + "/" + Objects.requireNonNull(fdir0.list())[i];
                    check(map, strAddress);
                }
            }
        }

        //Custom comparator
        Comparator<Map.Entry<String, Integer>> valCmp = (o1, o2) -> {
            // TODO Auto-generated method stub
            return o2.getValue() - o1.getValue();  // Sort in descending order. If you want to sort in ascending order, reverse it
        };
        //Convert the map into a list. A set of key s and value s of the map correspond to a storage space of the list
        List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet()); //Incoming maps entity
        list.sort(valCmp); //Sort the list

        return list;
    }

}


The sixth class (Interface): CorrectRoad

Function: it's just a function to find / which is mainly used in many places. If you write them one by one, there will be a lot of code.

code:

package finalExam;

public interface CorrectRoad {

    static int nameWhere(String str) {//Find the position of the last "/" in str
        int i;
        for (i = str.length() - 1; i >= 0; i--) {
            if (str.charAt(i) == '/') break;
        }
        return i;
    }

}

Class diagram:

Summary:

Every time this kind of curriculum design should not be treated too carelessly,! Attitude determines everything!.

As soon as you see this problem, don't panic. Now start from the main function. After building a main body, you can realize each small function successively, and then optimize your completed program. In this order, you can do the curriculum design with half the effort and get twice the result with half the effort.

Then, for those who don't understand, think for a few more days and try for a few more days. It's easy to be enlightened. It's really not. It's been tried for many days, but still not. Then refer to the codes of other big guys and read them.

Finally, please point out the problem!

Topics: Java Back-end