view raw
Rachamalla Kavya Sri Rachamalla Kavya Sri - 9 months ago 65
Java Question

Expression error detector [PARSER]

I have a question on parser, whenever a user enters the expression like

, He forgot to enter the other closing brace, and the program should give an error like
It's a wrong Expression
. Please help me out in doing this program, I have no idea how to start.


Use a stack data structure to validate the parenthesis matching.

If the character is '(','{','[' push the character onto the stack if the character is ')','}',']' respectively for the matching opening bracket then pop. Continue this till the stack is empty.


 import java.util.*;

 class ParenthesisMatching
    public static void main(String[] args) 
        Scanner scan = new Scanner(;
        Stack<Integer> stk = new Stack<Integer>();
        System.out.println("Enter expression");
        String exp =;        
        else System.out.println("unmatched");

    public static boolean isValid(String s) {
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');

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

        for (int i = 0; i < s.length(); i++) {
            char curr = s.charAt(i);

            if (map.keySet().contains(curr)) {
            } else if (map.values().contains(curr)) {
                if (!stack.empty() && map.get(stack.peek()) == curr) {
                } else {
                    return false;

        return stack.empty();