Use a stack to check .txt file for ('s, {'

2019-09-08 15:45发布

I am trying to write a method in java to search a text file that I imported for specific characters. The file is actually a java program that I designed and converted to a .txt file.

When an opening brace/bracket is found, I am supposed to add (push) it to a stack and then when a corresponding closing brace/bracket is found I am supposed to remove (pop) it from the stack.

The purpose is to see if I have the correct amount of ), }, ] and > to correspond with the (, {, [ and >. If they all match up the method should return true, if they don't it should return false.

Anyone know how I can write this?

标签: java file stack
1条回答
叛逆
2楼-- · 2019-09-08 16:39

This is the sample implementation for balancing the brackets in a input text file

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;

public class BalanceBrackets {
    private Stack<Character> symbolStack;

    public void balance(String inputText) {
        symbolStack = new Stack<Character>();
        for (int index = 0; index < inputText.length(); index++) {
            char currentSymbol = inputText.charAt(index);
            switch (currentSymbol) {
            case '(':
            case '[':
            case '{': 
                symbolStack.push(currentSymbol);
                break;

            case ')':
            case ']':
            case '}':
                if (!symbolStack.isEmpty()) {
                    char symbolStackTop = symbolStack.pop();
                    if ((currentSymbol == '}' && symbolStackTop != '{')
                            || (currentSymbol == ')' && symbolStackTop != '(')
                            || (currentSymbol == ']' && symbolStackTop != '[')) {
                        System.out.println("Unmatched closing bracket while parsing " + currentSymbol + " at " + index+1);
                        return;
                    }
                } else {
                    System.out.println("Extra closing bracket while parsing " + currentSymbol + " at character " + index+1);
                    return;
                }
                break;
            default:
                break;
            }
        }
        if (!symbolStack.isEmpty())
            System.out.println("Insufficient closing brackets after parsing the entire input text");
        else 
            System.out.println("Brackets are balanced");
    }

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader("D://input.txt"));
        String input = null;
        StringBuilder sb = new StringBuilder();
        while ((input = in.readLine()) != null) {
            sb.append(input);
        }
        new BalanceBrackets().balance(sb.toString());
    }
}
查看更多
登录 后发表回答