A counterexample in balanced parentheses 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&lt;String&gt; parenthesis = new Stack&lt;&gt;();

    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 &lt; l; i++) {
        System.out.println("Introduce an element");
       String e = x.next();
        parenthesis.push(e);
    }

    analysis(parenthesis);
}

public static void analysis(Stack&lt;String&gt; st) {

    Stack&lt;String&gt; closed = new Stack&lt;&gt;();//only for parentesis like this: )



    int ww = 0;
    while (!st.isEmpty() &amp;&amp; ww != 1) {
        String s =st.pop();
        if (0 == s.compareTo("(") &amp;&amp; !closed.isEmpty()) {
            closed.pop();
        } else if ((0 == s.compareTo("(")) &amp;&amp; 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");
    }

}
  }
May I suggest a simpler solution: 
You need only a counter. it is incremented by 1 whenever you encounter an openning parenthesis "(" and is decreased by 1 whenever you encounter a closing parenthesis ")" 
The input is invalid if the counter drops below zero or is not zero by the end of scanning.

EDIT
since OP specified they must use a stack, we can follow @JollyJoker's advice: counter increament is implemented by a push operation, counter decrement by a pop one.  counter falling below zero is implemented by attemt to pop when the stack is empty. by the end of scanning the stack has to be empty.