Java Stack Usage resolveSeparateIfSentence(List lines, int cursor, List target, String space)

Here you can find the source of resolveSeparateIfSentence(List lines, int cursor, List target, String space)

Description

resolve Separate If Sentence

License

Open Source License

Declaration

private static int resolveSeparateIfSentence(List<String> lines, int cursor, List<String> target,
            String space) 

Method Source Code

//package com.java2s;

import java.util.List;
import java.util.Stack;

public class Main {
    private static int resolveSeparateIfSentence(List<String> lines, int cursor, List<String> target,
            String space) {/*from   w w  w. j a  v  a  2  s .  c om*/
        int next = cursor + 1;
        int end = indexOfSeparateIfSentence(lines, lines.get(cursor), next);
        if (end != -1) {
            for (int i = cursor; i < end; i++) {
                target.add(lines.get(i));
            }
            target.add(lines.get(end) + " {");
            target.add(lines.get(end + 1));
            target.add(space + "}");
            return end - cursor + 1;
        } else {
            return 0;
        }
    }

    private static int indexOfSeparateIfSentence(List<String> lines, String beforeFragment, int cursor) {
        String currentLine = lines.get(cursor);
        currentLine = removeComments(currentLine);
        if (currentLine.matches("^.*\\s*\\{\\s*$")) {
            return -1;
        }
        String line = beforeFragment + currentLine;
        if (isBalance(line)) {
            return cursor;
        } else {
            return indexOfSeparateIfSentence(lines, line, ++cursor);
        }
    }

    private static String removeComments(String line) {
        int index = line.indexOf("//");
        if (index != -1) {
            return line.substring(0, index);
        }
        return line;
    }

    private static boolean isBalance(String line) {
        Stack<Character> stack = new Stack<>();
        for (char c : line.toCharArray()) {
            if ('(' == c) {
                stack.push(c);
            } else if (')' == c) {
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
}

Related

  1. normalizeAbsolutePath(String curDir)
  2. removeBackets(String cont)
  3. removeDotSegments(String relativePath)
  4. removeParenthesis(String text)
  5. resolveOneLineExpression(String line, String space, List target)
  6. split(final String str)
  7. split(String string, String token)