Parenthesis Learn programming Java



Lesson:

Dynamic Memory Management


Exercise:

Parenthesis


Objetive:

Implement a function to check if a sequence of open and closed parentheses is balanced. In other words, check if each open parenthesis corresponds to a closing one and they are correctly nested.

For example:

"(()()(()))" is OK
"(((()" is an 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();
	}
}



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.