判断代码中分隔符是否适当嵌套(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;
    }
}
发布了32 篇原创文章 · 获赞 40 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_27467365/article/details/84074501
今日推荐