Okay it is a bit of spaghetti code but why do I fail the test? I even tried with triple nested tags and the output seems correct....
package com.codegym.task.task19.task1918;
/*
Introducing tags
/Users/lilianetop/Desktop/taak1917.txt
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class Solution {
public static void main(String[] args) throws IOException {
//1. The program must read the file name from the console (use BufferedReader).
//2. try-with resources closes the stream automatically
String fileName;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
fileName = reader.readLine();
}
//3. The program must read the file's contents (use FileReader).
//4. The file input stream (FileReader) must be closed. (autoclosable)
//5. The program must write to the console all the tags that match the tag specified by the argument passed to the main method.
try (BufferedReader reader2 = new BufferedReader(new FileReader(fileName))) {
String line;
//problem is that the closing tag is on the next line so it is perceived as another String so I have to use a Stringbuilder
StringBuilder storage = new StringBuilder();
while (reader2.ready()) {
line = reader2.readLine();
storage.append(line);
}
//if args[0] = "span"; openingTag = <span and closing </span
String openingTag = "<" + args[0];
String closingTag = "</" + args[0] + ">";
//1 line that needs to be split per opening tag
List<String> tags = Arrays.asList(storage.toString().trim().replaceAll(openingTag, ("\n" + openingTag)).split("\n"));
/*for (String tag : tags) {
System.out.println(tag);
}
System.out.println();*/
for (int i = 0; i < tags.size(); i++) {
//step 1: check if line starts with opening tag and closing tag
if (tags.get(i).contains(openingTag) && tags.get(i).endsWith(closingTag)) {
// print it but only till first closing tag (inclusive)
System.out.println(tags.get(i).substring(0, tags.get(i).indexOf(closingTag)) + closingTag);
}
//step 2: if it contains an opening tag but not a closing tag
if (tags.get(i).contains(openingTag) && !tags.get(i).endsWith(closingTag) && ((i + 1) < tags.size())) {
System.out.print(tags.get(i));
//check the next line if it has 2 closing tags
int count = 0;
boolean b = true;
while (b) {
i++;
count++;
if (tags.get(i).indexOf(closingTag) == tags.get(i).length() - closingTag.length()) {
System.out.print(tags.get(i));
} else {
System.out.println(tags.get(i));
i -= count;
b = false;
}
}
}
}
}
}
}