Java Program to Check for balanced parenthesis by using Stacks

This is a Java Program to Check for balanced parenthesis by using Stacks. Parenthesis matching is commonly used for evaluating arithmetic expressions and in editors for validating syntax.

Here is the source code of the Java Program to check for balanced parenthesis by using stacks. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

/*
 *  Java Program to Check for balanced paranthesis by using Stacks
 */
 
import java.util.*;
 
public class ParenthesisMatching
{
    public static void main(String[] args) 
    {
        Scanner scan = new Scanner(System.in);
        /* Creating Stack */
        Stack<Integer> stk = new Stack<Integer>();
        System.out.println("Parenthesis Matching Test\n");
        /* Accepting expression */
        System.out.println("Enter expression");
        String exp = scan.next();        
        int len = exp.length();
        System.out.println("\nMatches and Mismatches:\n");
        for (int i = 0; i < len; i++)
        {    
            char ch = exp.charAt(i);
            if (ch == '(')
                stk.push(i);
            else if (ch == ')')
            {
                try
                {
                    int p = stk.pop() + 1;
                    System.out.println("')' at index "+(i+1)+" matched with ')' at index "+p);
                }
                catch(Exception e)
                {
                    System.out.println("')' at index "+(i+1)+" is unmatched");
                }
            }            
        }
        while (!stk.isEmpty() )
            System.out.println("'(' at index "+(stk.pop() +1)+" is unmatched");
    }
}
Parenthesis Matching Test
 
Enter expression
(a+(b*c)-d)
 
Matches and Mismatches:
 
')' at index 8 matched with ')' at index 4
')' at index 11 matched with ')' at index 1
 
 
 
Parenthesis Matching Test
 
Enter expression
((x+y/(z-w))
 
Matches and Mismatches:
 
')' at index 11 matched with ')' at index 7
')' at index 12 matched with ')' at index 2
'(' at index 1 is unmatched
 
 
 
Parenthesis Matching Test
 
Enter expression
(a+b*(c-d)-(e-f/(g+h*(k-i)/(l-j+k
 
Matches and Mismatches:
 
')' at index 10 matched with ')' at index 6
')' at index 26 matched with ')' at index 22
'(' at index 28 is unmatched
'(' at index 17 is unmatched
'(' at index 12 is unmatched
'(' at index 1 is unmatched

Related posts:

Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Java Program to Generate Random Numbers Using Middle Square Method
Java Program to Generate a Graph for a Given Fixed Degree Sequence
Java Program to Implement Rolling Hash
Java Program to Implement VList
Java Program to Use rand and srand Functions
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Arrays.asList vs new ArrayList(Arrays.asList())
Java 14 Record Keyword
Java Program to Find Nearest Neighbor for Static Data Set
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
Java Program to Perform Optimal Paranthesization Using Dynamic Programming
Spring REST API + OAuth2 + Angular (using the Spring Security OAuth legacy stack)
Java Program to Implement Lloyd’s Algorithm
Java Program to Implement Sorted Circular Doubly Linked List
Form Validation with AngularJS and Spring MVC
Java Program to Implement Solovay Strassen Primality Test Algorithm
Java Program to Generate Random Numbers Using Multiply with Carry Method
JWT – Token-based Authentication trong Jersey 2.x
Java Program to Compute the Volume of a Tetrahedron Using Determinants
Java Program to Describe the Representation of Graph using Incidence List
Generic Constructors in Java
Hướng dẫn Java Design Pattern – State
Java Program to Perform Search in a BST
Java Program to Implement Find all Cross Edges in a Graph
Guide to the ConcurrentSkipListMap
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Spring Boot - Cloud Configuration Client
Split a String in Java
Java Program to Check Whether Graph is DAG
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Java Program to Find Minimum Element in an Array using Linear Search