Java Program to check the Balanced Parentheses

              This is one of the Stack Applications. To implement this concept, a stack is used to store the input.

Here’s the implementation.

Java implementation:

Class : PaenthesisCheckerEg

Variables:

‘stack1’ – new object for Stack.

‘exp’ – input expression.

‘c’ – it is a character data type. It stores a character at a time to check.

‘top’ -it stores the top element.

Member functions:

isitBalanced() :

This function is used to check the balance.

main():

it gets the input from user.

Calls the isitBalanced() function and prints the result.

Program:

import java.util.Stack;

import java.util.Scanner;

public class ParenthesisCheckerEg {

    public static boolean isitBalanced(String exp) {

        Stack<Character> stack1 = new Stack<>();

        for (char c : exp.toCharArray()) {

            // check if it is an opening bracket, push it onto the stack

            if (c == '(' || c == '{' || c == '[') {

                stack1.push(c);

            }

            // check if it's a closing bracket, check if it matches the top of the stack

            else if (c == ')' || c == '}' || c == ']') {

                if (stack1.isEmpty()) return false;

                char top = stack1.pop();

                if ((c == ')' && top != '(') ||

                    (c == '}' && top != '{') ||

                    (c == ']' && top != '[')) {

                    return false;

                }

            }

        }

        // check for stack is empty at the end, parentheses are balanced

        return stack1.isEmpty();

    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a input with parenthesis ( [ {: ");

        String exp = scanner.nextLine();

        if (isitBalanced(exp)) {

            System.out.println("The expression with parentheses is balanced.");

        } else {

            System.out.println("The expression is not balanced.");

        }

    }

}

Output:

C:\raji\blog>javac ParenthesisCheckerEg.java

C:\raji\blog>java ParenthesisCheckerEg

Enter a input with parenthesis ( [ {: {[()]}

The expression with parentheses is balanced.

C:\raji\blog>java ParenthesisCheckerEg

Enter a input with parenthesis ( [ {: ({}]

The expression is not balanced.

This is the simple java implementation of  Balanced ParenthesisChecker. Hope this code is useful to you. Keep Coding!!!

No comments:

Post a Comment