Hey I am doing a programming assignment and we have to match parentheses in a String. We have to output an Error message such as the following:
Sample I/O:
Enter a string to test: ( < [ { } ( { > ) ] >
error: '>' does not match with '{'.
I am trying to print this message in my isBalanced() method however it will not print the System.out.println() however it is reaching that code block (otherwise it would never return false) which it is. I think the problem lies in my main method but I have been trying for a while now and I am stumped! Any help is appreciated. Thanks,
Kyle.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.EmptyStackException;
import java.util.Stack; //using java's default stack in this case as it has more extraneous error checking
public class Question3 {
private static final String OPEN = "([{<";
private static final String CLOSED = ")]}>";
public static void main(String[] args) throws IOException {
BufferedReader inKb = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter a test string:");
String input = inKb.readLine();
boolean successful = isBalanced(input);
System.out.println(successful);
}
public static void printError(char ch, char expected) {
System.out.println("Error: '" + ch + "' does not match with '"
+ expected + "'");
}
private static boolean isOpen(char bracket) {
return OPEN.indexOf(bracket) >= 0;
}
private static boolean isClosed(char bracket) {
return CLOSED.indexOf(bracket) >= 0;
}
private static boolean matches(char openBracket, char closedBracket) {
return OPEN.indexOf(openBracket) == CLOSED.indexOf(closedBracket);
}
public static boolean isBalanced(String input) {
Stack<Character> stack = new Stack<Character>();
try {
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (isOpen(ch)) {
stack.push(ch);
} else if (isClosed(ch)) {
char corBracket = stack.pop(); // pop corresponding bracket
if (!matches(ch, corBracket)) {
System.out.println("Print Test!"); //Not printing?
return false;
}
}
}
} catch (EmptyStackException ex) {
return false;
}
return stack.isEmpty(); //if stack is empty then the corresponding bracket wasn't found!
}
}