Advertisement
FahimFaisal

Stack_parentThesisChecker

Mar 8th, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package parentThesisBalance;
  7.  
  8. import java.util.Scanner;
  9. import java.util.*;
  10.  
  11. public class CheckerPT {
  12.  
  13.     /**
  14.      * @param args the command line arguments
  15.      */
  16.     public static void main(String[] args) {
  17.         try{
  18.             Stack stack = new Stack();
  19.             Scanner sc = new Scanner(System.in);
  20.             System.out.println("Enter a expression");
  21.             String exp = sc.nextLine();
  22.             boolean flag=false;
  23.             for (int c = 0; c < exp.length(); c++) {
  24.                 char ch = exp.charAt(c);
  25.                 if (ch == '{' || ch == '(' || ch == '[') {
  26.                     stack.push(ch);
  27.                 }
  28.                 else if(ch=='}'||ch==')'||ch==']'){
  29.                         if(stack.isEmpty()){
  30.                             int found=exp.indexOf(ch);
  31.                             System.out.println("Error at character "+ ++found);
  32.                             System.out.println(ch+" not opened");
  33.                         }
  34.                         char popch=(char)stack.pop();
  35.                         int index=exp.indexOf(popch);
  36.                     if((ch=='}' && popch=='{')||(ch==')' && popch=='(')||(ch==']' && popch=='['))
  37.                         flag=true;
  38.                     else{
  39.                         flag=false;
  40.                         System.out.println("Expression is NOT correct");
  41.                         System.out.println("Error at character# "+ ++index);
  42.                         System.out.println(popch+" not closed");
  43.                         break;
  44.                     }
  45.                 }
  46.             }
  47.             if(flag)
  48.                     System.out.println("The expression is correct");
  49.             }catch(Exception e){
  50.             System.out.println(e);
  51.         }
  52.     }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement