Reputation: 205
I am trying to implement a stack in java, I want to be able to return the row and the column of the open bracket of its companion that returned an error. For instance:
public static foo() {
System.out.println ("foo"
}
this should produce an error when compiled, what I want to return is some error in the form of:
"ERROR: row 2 column 23 '(' found, and expected ')' at row 2 column 29 but found ' ' instead."
is this possible with a linkedLIst of linkedLists? Or would another tool be better for this application. I would like the push(), pop() and peek() methods to preserve a constant behavior.
Thank you
Upvotes: 1
Views: 200
Reputation: 14458
Use a built-in Stack object. No need to reinvent the wheel and create your own version of a standard library class.
As pertains to printing errors for unmatched braces, I would recommend creating a class
public final class Brace {
private final char openBrace;
private final char closeBrace;
private final int row;
private final int col;
public Brace(char openBrace, int row, int col) {
this.openBrace = openBrace;
this.row = row;
this.col = col;
switch (openBrace) {
case '(':
closeBrace = ')';
break;
case '{':
closeBrace = '}';
break;
case '[':
closeBrace = ']';
break;
default:
throw new IllegalArgumentException("Unsupported opening brace");
}
}
public boolean isClosingBrace(char ch) {
return closeBrace == ch;
}
}
and keeping a Stack<Brace>
in your program. Then, as you move through the file, you can push opening braces onto the stack and, as you reach each closing brace, ensure that it is the closing brace for the brace at the top of the stack. If it isn't, you have already stored the row and column to print in the error message.
Upvotes: 2