Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package matching_brackets_exercise;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Scanner;
- public class MatchingBracketsWithList {
- public boolean checkBracketsWithList(String expression) {
- HashMap<Character, Character> map = new HashMap<>();
- map.put('{', '}');
- map.put('(', ')');
- map.put('[', ']');
- List<Character> list = new ArrayList<>();
- char[] charArray = expression.toCharArray();
- for (Character c : charArray)
- if (map.keySet().contains(c)) {
- list.add(c);
- } else if (map.values().contains(c)) {
- if (!list.isEmpty() && map.get(list.get(list.size() - 1)) == c) list.remove(list.size() - 1);
- else return false;
- }
- return list.isEmpty();
- }
- public static void main(String[] args) {
- MatchingBracketsWithList pc = new MatchingBracketsWithList();
- File file = new File("CommonName.java");
- try (Scanner in = new Scanner(file)) {
- StringBuilder expression = new StringBuilder();
- while (in.hasNextLine()) {
- expression.append(in.nextLine());
- }
- if (pc.checkBracketsWithList(expression.toString())) System.out.println(file.getName() + " has balanced brackets");
- else System.out.println(file.getName() + " does not have has balanced brackets");
- } catch (FileNotFoundException ex) {
- System.out.println(ex);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement