如何用栈实现Java文件的花括号开闭数量匹配检查?
Hey there! I see you've got a solid start with your stack-based brace checker, but right now it's reading from console input instead of a Java file, plus there's a small issue with how you're validating the braces (just counting doesn't catch mismatched order like }{). Let's fix both problems step by step.
First: Replace Console Input with File Reading
Instead of using Scanner to read from the console, we'll use BufferedReader and FileReader to read the contents of a Java file. You'll need to handle IOException since file operations can throw errors.
Second: Fix the Brace Validation Logic
Your current code pushes every character to the stack and then counts { and } as you pop them—but this doesn't account for mismatched braces (like closing a brace that wasn't opened first). We'll adjust the logic to:
- Only push
{to the stack when we encounter them - When we see
}, check if the stack is empty (meaning we have an unmatched closing brace) or if the top of the stack is{(if so, pop it; if not, we have a mismatch) - At the end, if the stack is empty, all braces are properly matched
Modified Complete Code
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Llaves1 { private int t = -1; private char[] pila; Llaves1(int size) { this.pila = new char[size]; } public int size() { return (t + 1); } public boolean isEmpty() { return t == -1; } public void push(char x) { if (this.size() == this.pila.length) { System.out.println("Pile is already full."); } else { this.pila[++t] = x; } } public char pop() { if (isEmpty()) { System.out.println("Empty Pile."); return '\0'; // Return a placeholder to avoid index out of bounds } return pila[t--]; } public char top() { if (isEmpty()) { System.out.println("Empty pile."); return '\0'; } return pila[t]; } public static void main(String[] args) { // Check if a file path is provided as an argument if (args.length == 0) { System.out.println("Please provide the path to your Java file as a command line argument."); return; } String filePath = args[0]; StringBuilder fileContent = new StringBuilder(); // Read the Java file try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; while ((line = reader.readLine()) != null) { fileContent.append(line); } } catch (IOException e) { System.out.println("Error reading the file: " + e.getMessage()); return; } String cadena = fileContent.toString(); Llaves1 a = new Llaves1(cadena.length()); boolean isBalanced = true; for (int i = 0; i < cadena.length(); i++) { char temp = cadena.charAt(i); if (temp == '{') { a.push(temp); } else if (temp == '}') { if (a.isEmpty() || a.top() != '{') { isBalanced = false; break; // No need to check further if we find a mismatch } a.pop(); // Pop the matching opening brace } // Ignore all other characters since we only care about curly braces } // After processing all characters, check if stack is empty and no mismatches found if (isBalanced && a.isEmpty()) { System.out.println("All curly braces are properly closed and matched."); } else { System.out.println("Curly braces are either mismatched or not fully closed."); } } }
Key Changes Explained
- File Reading: We use
BufferedReaderwith a try-with-resources block (so the reader is automatically closed) to read the entire file into aStringBuilder. - Command Line Argument: The program now expects you to pass the Java file path as a command line argument (e.g.,
java Llaves1 MyClass.java). - Brace Validation: We only process
{and}. When we hit a}, we immediately check if there's a matching{on the stack. If not, we mark the braces as unbalanced and stop checking early. - Error Handling: Added checks for missing file arguments and file reading errors, plus fixed the
pop()andtop()methods to return a placeholder when the stack is empty to avoid runtime errors.
How to Use
- Compile the code:
javac Llaves1.java - Run it with your Java file path:
java Llaves1 path/to/your/file.java
内容的提问来源于stack exchange,提问作者Chanell

