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:

Một số ký tự đặc biệt trong Java
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Quick Guide to java.lang.System
Java Program to Implement Efficient O(log n) Fibonacci generator
Converting a Stack Trace to a String in Java
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
Rate Limiting in Spring Cloud Netflix Zuul
Hướng dẫn Java Design Pattern – Transfer Object
Finding Max/Min of a List or Collection
Java Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
Spring Boot - Web Socket
Understanding Memory Leaks in Java
Connect through a Proxy
Java Program to Implement Sorted Circularly Singly Linked List
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
Spring Security – security none, filters none, access permitAll
RestTemplate Post Request with JSON
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Queue và PriorityQueue trong Java
Java Program to Find the Nearest Neighbor Using K-D Tree Search
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
Java Program to Implement Binary Heap
Hướng dẫn tạo và sử dụng ThreadPool trong Java
Get the workstation name or IP
Send email with authentication
Java Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
Converting a Stack Trace to a String in Java
Jackson JSON Views
Java Program to Implement Gaussian Elimination Algorithm
Life Cycle of a Thread in Java