Parenthesis Learn programming Java

Lesson:

Dynamic Memory Management


Exercise:

Parenthesis 16


Objetive:

Implement a function to check if a sequence of opened and closed parenthesis is balanced, in other words, if each opened parenthesis corresponds to one closed and they are also well nested.

For example:

(()()(())) OK
(((() ERROR


Code:

package Expression;
import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		String expresion = "()()()()()()";
		boolean expresionMal = false;

		Stack pila = new Stack();

		for (int i = 0; i < expresion.length(); i++)
		{
			if (expresion.charAt(i) == '(')
			{
				pila.push(expresion.charAt(i));
			}
			else if (expresion.charAt(i) == ')')
			{
				if (pila.size() > 0)
				{
					pila.pop();
				}
				else
				{
					expresionMal = true;
				}
			}
		}
		if (expresionMal)
		{
			System.out.println("ERROR");
		}
		else
		{
			System.out.println("OK");
		}
		new Scanner(System.in).nextLine();
	}
}