Here you can find the source of resolveSeparateIfSentence(List
private static int resolveSeparateIfSentence(List<String> lines, int cursor, List<String> target, String space)
//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(); } }