Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. package matching_brackets_exercise;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Scanner;
  9.  
  10. public class MatchingBracketsWithList {
  11.  
  12.     public boolean checkBracketsWithList(String expression) {
  13.         HashMap<Character, Character> map = new HashMap<>();
  14.         map.put('{', '}');
  15.         map.put('(', ')');
  16.         map.put('[', ']');
  17.  
  18.         List<Character> list = new ArrayList<>();
  19.         char[] charArray = expression.toCharArray();
  20.         for (Character c : charArray)
  21.             if (map.keySet().contains(c)) {
  22.                 list.add(c);
  23.             } else if (map.values().contains(c)) {
  24.                 if (!list.isEmpty() && map.get(list.get(list.size() - 1)) == c) list.remove(list.size() - 1);
  25.                 else return false;
  26.             }
  27.         return list.isEmpty();
  28.     }
  29.  
  30.  
  31.     public static void main(String[] args) {
  32.  
  33.         MatchingBracketsWithList pc = new MatchingBracketsWithList();
  34.         File file = new File("CommonName.java");
  35.         try (Scanner in = new Scanner(file)) {
  36.             StringBuilder expression = new StringBuilder();
  37.             while (in.hasNextLine()) {
  38.                 expression.append(in.nextLine());
  39.             }
  40.             if (pc.checkBracketsWithList(expression.toString())) System.out.println(file.getName() + " has balanced brackets");
  41.             else System.out.println(file.getName() + " does not have has balanced brackets");
  42.         } catch (FileNotFoundException ex) {
  43.             System.out.println(ex);
  44.         }
  45.  
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement