In this program I had to analyse if the parenthesis given are well balanced. For instance, input (())
is correct and input ())(()
is incorrect. I've tested with other similar inputs, so my question is: can my code fail with some weird expression (using parentheses) or will it always work correctly?
public class Main {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
Stack<String> parenthesis = new Stack<>();
System.out.println("Introduce the length of your expression");
int l = x.nextInt();
System.out.println("Introduce your expression");
x.nextLine();
for (int i = 0; i < l; i++) {
System.out.println("Introduce an element");
String e = x.next();
parenthesis.push(e);
}
analysis(parenthesis);
}
public static void analysis(Stack<String> st) {
Stack<String> closed = new Stack<>();//only for parentesis like this: )
int ww = 0;
while (!st.isEmpty() && ww != 1) {
String s =st.pop();
if (0 == s.compareTo("(") && !closed.isEmpty()) {
closed.pop();
} else if ((0 == s.compareTo("(")) && closed.isEmpty()) {
System.out.println("incorrect expression.");
ww = 1;
} else {
closed.push(s);
}
}
if (ww == 1) {
System.out.println();
} else if (!closed.isEmpty()) {
System.out.println("incorrect espression");
} else {
System.out.println("correct");
}
}
}
((x)
would pass, when it shouldn't \$\endgroup\${}[]()
parens. So({()[]}[])
would be legal but({())}
would not be. Now it is not so simple as just counting how many opens and closed you see; you have to actually use the contents of the stack to solve this problem, and not, as others have noted, simply use the stack as a complicated integer. \$\endgroup\$(
, push it on the stack. When you see a)
, check to see if the stack is empty; if it is, you have a bad input. If not, pop the stack. If you end up with a non-empty stack, you have a bad input. Otherwise you have a good input. This program should be much shorter and simpler than yours. \$\endgroup\$NullPointerException
s (whens == null
) than the equals in my comment. \$\endgroup\$