1. 程式人生 > >判斷程式碼中分隔符是否適當巢狀(Properly nested Delimiters)

判斷程式碼中分隔符是否適當巢狀(Properly nested Delimiters)

Java程式可以具有以下型別的分隔符:{,},(,),[和]。在正確的Java程式中,必須正確巢狀這些分隔符。每個左分隔符{,(和[作為開啟範圍,並考慮每個右邊界定}},和],關閉由相應左分隔符開啟的範圍。如果開啟的每個作用域最終都被關閉,則包含這些分隔符的字串具有正確的分隔符巢狀,並且以最後開啟的第一個閉合方式開啟和關閉作用域。

編寫一個程式,讀取包含Java原始碼的檔案,並檢查它是否正確巢狀分隔符。你的程式應該從檔案中讀取原始碼並將其列印到螢幕上。如果檔案已正確巢狀,則會將所有檔案列印到螢幕上並列印一條訊息,表明檔案已正確巢狀。如果檔案未正確巢狀,則只要檢測到不正確的巢狀,就會立即停止將檔案複製到螢幕,並且程式會打印出檔案有錯誤的訊息。

為了簡化任務,您可以假設這些分隔符不會出現在註釋和字串文字中,並且它們不會作為字元文字出現在程式中。

A Java program can have the following type of delimiters: {, }, (, ), [, and ]. In a correct Java program, these delimiters must be properly nested. Think of each left delimiter {, (, and [ as opening a scope, and think of each right delimiter }, ), and ] as closing a scope opened by a corresponding left delimiter. A string of characters containing these delimiters has proper nesting of delimiters if each scope that is opened is eventually closed, and the scopes are opened and closed in a last-opened-first-closed fashion.

Write a program that reads a file containing Java source code and checks it for proper nesting of delimiters. Your program should read the source code from the file and print it to the screen. If the file is properly nested, all of it is printed to the screen and a message is printed that the file is properly nested. If the file is not properly nested,  then copying of the file to the screen stops as soon as improper nesting is detected, and your program prints a message that the file has errors.

To simplify your task, you may assume these delimiters do not appear inside of comments and string literals, and that they do not appear in the program as character literals.

Driver class

package ProperlyNestedDelimiters;

/** * filename: ProperlyNestedDelimiters.java * package:ProperlyNestedDelimiters * @author Xu Wanxiang * date:2018 * description:Run Properly nested Delimiters. * @version 1.0 */ public class Driver {     /**      * Run Properly nested Delimiters.      * @param args A reference to a string array      */     public static void main(String[] args) {         new Controller();     } }

Controller class

package ProperlyNestedDelimiters;
import java.util.*;

/**
 * filename: ProperlyNestedDelimiters.java
 * package:ProperlyNestedDelimiters
 * @author:Xu Wanxiang
 * date:2018
 * description: this class let the user to type in the filepath of the file they want to check.
 * @version 1.0
 */
public class Controller {
    /**
     * description: check if the Delimiters of file is Properly Nested.
     * @return - IPND
     * @throws Exception
     */
    public Controller(){
        System.out.println("input the filename please");
        Scanner sc = new Scanner(System.in);
        String fileName = sc.nextLine();
        new ProperlyNestedDelimiters(fileName);
    }
}

ProperlyNestedDelimiters class

package ProperlyNestedDelimiters;

/**
 * filename: ProperlyNestedDelimiters.java
 * package:ProperlyNestedDelimiters
 * @author:Xu Wanxiang
 * date:2018
 * description: this class check if all Delimiters are Properly Nested.
 * @version 1.0
 */

public class ProperlyNestedDelimiters{

    /**
     * description: check if the Delimiters of file is Properly Nested.
     * @return - IPND
     * @throws Exception
     */
    public ProperlyNestedDelimiters(String fileName){
        isProperlyNestedDelimiters IPND = new isProperlyNestedDelimiters();
        if (IPND.isProperlyNestedDelimiters(fileName)){
            System.out.println("All delimiters are properlyNested");
        }else{
            System.out.println("Some delimiters are not properlyNested");
        }
    }
}

isProperlyNestedDelimiters class

package ProperlyNestedDelimiters;

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

/**
 * filename: isProperlyNestedDelimiters.java
 * package:ProperlyNestedDelimiters
 * @author:Xu Wanxiang
 * date:2018
 * description: this class check if all Delimiters are Properly Nested.
 * @version 1.0
 */
public class isProperlyNestedDelimiters {

    /**
     * The list of objects of this stack
     */

    // the operator stack
    private Stack<Character> operatorStack;

    // the operators
    private   static   final  String OPERATORS =  "{}()[]" ;

    // the precedence of the operators
    private   static   final   int [] PRECEDENCE = { 1 ,  1 ,  2 ,  2 , - 1 , - 1 };

    /**
     * description: check if the Delimiters of file is Properly Nested.
     * @return - IPND
     * @throws Exception
     */
    public boolean isProperlyNestedDelimiters(String filePath){
        operatorStack = new Stack<Character>();
        boolean IPND = true;
        String FileData = getFileData(filePath);
        int flag = 0;
        for(int i = 0;i<FileData.length();i++){
            char temp = FileData.charAt(i);
            System.out.print(temp);
            if((temp == '[')||(temp == '(')||(temp == '{')||(temp == ')')||(temp == ']')||(temp == '}')) {
                if (temp == '[') {
                    operatorStack.push(temp);
                } else if (temp == '(') {
                    operatorStack.push(temp);
                } else if (temp == '{') {
                    operatorStack.push(temp);
                } else {
                    char temp1 = (char) operatorStack.pop();
                    if ((temp1 == '(' && temp == ')') || (temp1 == '[' && temp == ']') || (temp1 == '{' && temp == '}')) {
                        flag = 1;
                    } else {
                        flag = 0;
                        break;
                    }
                }
            }
        }
        if(flag == 0 || operatorStack.size() > 0){
            System.out.println("no");
            IPND = false;
        }else{
            System.out.println("yes");
        }
        return IPND;

    }

    /**
     * description: check if the Delimiters of file is Properly Nested.
     * @return - IPND
     * @throws Exception
     */
    public String getFileData(String fileName){
        ArrayList<String> arrayList = new ArrayList<String>();
        StringBuilder SB = new StringBuilder();
        String FileData = null;

        try {
            FileReader fr = new FileReader(fileName);
            BufferedReader br = new BufferedReader(fr);
            String str;
            while ((str = br.readLine()) != null) {
                if(null != str || !str.trim().equals("")){
                    arrayList.add(str);
                }
            }
            Iterator AL = arrayList.iterator();
            while (AL.hasNext()){
                SB.append(AL.next().toString());
            }
            fr.close();
            br.close();
            FileData = SB.toString();
        }catch (IOException e){
            System.out.print("Exception");
        }
        return FileData;
    }
}