View Full Version : Stacks, Parenthesis Checker

04-26-2009, 03:33 PM
I need to create a program that can read an entire java file and put the whole thing into a string.

File file = new File("test.java");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;

reader = new BufferedReader(new FileReader(file));
String text = null;

while ((text = reader.readLine()) != null)
} catch (FileNotFoundException e)
} catch (IOException e)
} finally
if (reader != null)
} catch (IOException e)

String contentstoTest = contents.toString();

Thats the easy part. The file test.java is in the string contentstoString. However, after that i need to use stacks to find all the (, { and [, and match them accordingly to their closing ), } and ]. Perfectly, the program will tell me which bracket is unclosed, but for the time being, i would be happy enough just to find a solution that told me if it was balanced or not.
I have found a few variations of a similar program on the internet, but am finding it hard to understand exactly what i need to do to write my own.

public class MatchParen {

private boolean matching = true;

private java.util.Stack s = new java.util.Stack();

public boolean isMatching() {
return matching && s.isEmpty();

public void add(char c) {
Character m = leftMatch(c); // or use leftMatch2
if (m == null) // c is not a parenthesis
; // do nothing (i.e., ignore it)
else if (m.charValue() == c) // c is some kind of left parenthesis
s.push(m); // push a Character version, m
else { // c is some kind of right paren
if (s.isEmpty() || !s.pop().equals(m))
matching = false; // couldn't pop a matching left paren, m

public void add(String s) {
for (int i=0; i < s.length(); i++)

public static Character leftMatch(char c) {
switch (c) {
case '(':
case ')':
return new Character('(');
case '[':
case ']':
return new Character('[');
case '{':
case '}':
return new Character('{');
return null;

That is the other part of my code, and it does tell me weather or not its balenced. However, like i stated earlier, i would love it if i could change the program to display what line the unmatched symbol is located. Any assistance is greatly appreciated, thanks!

06-19-2009, 02:54 PM
Now that is what I would call a stack of stacks.

What a fantastic picture.

And the background is what I fell makes it so spectacular.

The stacks on thier own would have been good, with the other kites and goings on, SUPER cool.