Advertisement
Kulas_Code20

checker

Sep 18th, 2021
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. package practice;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.io.IOException;
  8.  
  9. public class ParenthesisChecker {
  10.  
  11.     public static void main(String[] args) throws IOException {
  12.         File file = new File("C:\\Users\\Fujitsu\\Documents\\Java Files\\Data Structure and Algo\\src\\practice\\Test.txt");
  13.         try {
  14.             BufferedReader br = new BufferedReader(new FileReader(file));
  15.             Stack st = new StackLinked();
  16.             String data = "";
  17.             String msg = "";//"un-balanced";
  18.             while((data = br.readLine()) != null) {
  19.                 System.out.print(data + " ");
  20.                 char[] ch = data.toCharArray();
  21.                 //Traverse array
  22.                 for(int i = 0; i < ch.length; i++) {
  23.                     char c = ch[i];
  24.                     char b='\u0000';
  25.                     //If the current character is starting bracket, then push them in a stack
  26.                     if(c == '(' || c == '{' || c == '[' || c == '<') {
  27.                         st.push(c);
  28.                     } else if(c == ')' || c == '}' || c == ']' || c == '>') {
  29.                         if (!st.isEmpty()) {
  30.                             b = (char) st.peek();//.toString().charAt(0);
  31.                             if (b == '(' || b == '{' || b == '[' || b == '<') {
  32.                                 st.pop();
  33.                             } else {
  34.                                 st.push(c);
  35.                             }
  36.                         }
  37.                     }
  38.                     if (st.isEmpty()) {
  39.                         msg = "balanced";
  40.                     } else {
  41.                         msg = "unbalanced";
  42.                     }
  43.                 }
  44.                 System.out.println(msg);
  45.             }
  46.             br.close();
  47.         }catch(FileNotFoundException e) {
  48.             // TODO Auto-generated catch block
  49.             e.printStackTrace();
  50.         }
  51.     }
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement