| 7 | import java.util.Scanner; |
| 8 | |
| 9 | public class Demo |
| 10 | { |
| 11 | public static void main(String[] args) |
| 12 | { |
| 13 | String expression; |
| 14 | |
| 15 | Scanner scan = new Scanner(System.in); |
| 16 | |
| 17 | System.out.print("Enter an expression with parentheses : "); |
| 18 | expression = scan.nextLine(); |
| 19 | |
| 20 | if(isValid(expression)) |
| 21 | System.out.println("Valid expression"); |
| 22 | else |
| 23 | System.out.println("Invalid expression"); |
| 24 | scan.close(); |
| 25 | } |
| 26 | |
| 27 | |
| 28 | public static boolean isValid(String expr) |
| 29 | { |
| 30 | StackA st = new StackA(); |
| 31 | |
| 32 | char ch; |
| 33 | for(int i=0; i<expr.length(); i++) |
| 34 | { |
| 35 | if(expr.charAt(i)=='(' || expr.charAt(i)=='{' || expr.charAt(i)=='[') |
| 36 | st.push(expr.charAt(i)); |
| 37 | |
| 38 | if(expr.charAt(i)==')' || expr.charAt(i)=='}' || expr.charAt(i)==']') |
| 39 | if(st.isEmpty()) |
| 40 | { |
| 41 | System.out.println("Right parentheses are more than left parentheses"); |
| 42 | return false; |
| 43 | } |
| 44 | else |
| 45 | { |
| 46 | ch=st.pop(); |
| 47 | if(!matchParentheses(ch,expr.charAt(i))) |
| 48 | { |
| 49 | System.out.println("Mismatched parentheses are : "); |
| 50 | System.out.println(ch + " and " + expr.charAt(i)); |
| 51 | return false; |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | if(st.isEmpty()) |
| 57 | { |
| 58 | System.out.println("Balanced Parentheses"); |
| 59 | return true; |
| 60 | } |
| 61 | else |
| 62 | { |
| 63 | System.out.println("Left parentheses are more than right parentheses"); |
| 64 | return false; |
| 65 | } |
| 66 |
nothing calls this directly
no outgoing calls
no test coverage detected