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]);
            }
        }
    }
}

Leave a Reply

%d bloggers like this: