Categories
Class 11 Class 12

Matching Parentheses In An Expression in Java

Write a program in Java that will match parentheses in an expression entered by the user.

Use the following method prototype to print the position of matched pair and report the position if unmatched:

void printMatchedPairs(String exp)

import java.io.*;
class Parentheses{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Expression: ");
        String exp = br.readLine();
        printMatchedPairs(exp);
    }
    public static void printMatchedPairs(String exp){
        char stack[] = new char[exp.length()];
        int pos[] = new int[exp.length()];
        int top = -1;
        for(int i = 0; i < stack.length; i++){
            char p = exp.charAt(i);
            if(p == '('){
                stack[++top] = '(';
                pos[top] = i + 1;
            }
            else if(p == ')'){
                if(top == -1){
                    System.out.println("Unmatched ) at position " + (i + 1));
                }
                else{
                    System.out.println("Matched pair: " + pos[top] + ", " + (i + 1));
                    top--;
                }
            }
        }
        if(top != -1){
            for(int i = 0; i <= top; i++){
                System.out.println("Unmatched ( at position " + pos[i]);
            }
        }
    }
}

By admin

I am a Computer Science teacher in one of the renowned schools in India. I teach Java programming language to my students, and I maintain a website happycompiler.com

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.