Can't figure out why this won't accept. It works with every example I've thrown at it. This is why CodeGym is so frustrating some times. I've created numerous working exercises that for some unknown reason, the verifier has a problem with. But this example below does exactly what it's supposed to do. If someone can show me otherwise, I'd love to know!
package com.codegym.task.task19.task1918;
/*
Introducing tags
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName1 = reader.readLine();
reader.close();
if(args.length == 0)
return;
String fileContents = "";
try(BufferedReader fileReader = new BufferedReader(new FileReader(fileName1))) {
while(fileReader.ready()) {
fileContents += fileReader.readLine();
}
}
List<Integer> openTagIndeces = new ArrayList<>();
List<Integer> closeTagIndeces = new ArrayList<>();
int openOffSet = 0;
while(fileContents.indexOf("<"+args[0], openOffSet) > -1) {
int index = fileContents.indexOf("<"+args[0], openOffSet);
openTagIndeces.add(index);
openOffSet = index+1;
}
int closeOffSet = 0;
while(fileContents.indexOf("/"+args[0], closeOffSet) > -1) {
int index = fileContents.indexOf("/"+args[0], closeOffSet);
closeTagIndeces.add(index);
closeOffSet = index+1;
}
//System.out.println(openTagIndeces);
//System.out.println(closeTagIndeces);
List<String> outputData = new ArrayList<>();
for(int i=0; i<openTagIndeces.size(); i++) {
int startIndex = openTagIndeces.get(i);
int closeIndex = closeTagIndeces.get(i);
//Figure out how many open tag indexes are less than current close index. This indicates nested open tags
int openTagCounter = 0;
int openTagIteration = i;
while(openTagIteration+1 < openTagIndeces.size() && openTagIndeces.get(openTagIteration+1) < closeIndex) {
openTagCounter++;
openTagIteration++;
}
//Similarly, we need to know how many close tags are greater than current open index. We need to go from
//current open index to next greatest close index. This gives us two offsets. The open offset above
//and the close offset below. We add these values together and we get the correct corresponding close tag
int closeTagCounter = 0;
int closeTagIteration = i;
while(closeTagIteration-1 >= 0 && startIndex < closeTagIndeces.get(closeTagIteration-1)) {
closeTagCounter--;
closeTagIteration--;
}
outputData.add(fileContents.substring(startIndex, closeTagIndeces.get(i+openTagCounter+closeTagCounter) + args[0].length() + 2));
}
//for(String s : outputData)
//System.out.println(s);
}
}