Hello!
Maybe some one will be able to find mistake that I cannot see myself.
First I read all the lines from file, then I replace every sign of new line '\n' with space. Next I enter double for loop. In first loop I check if words[i] is not null, then I assing value to first word in pair. Finally I enter inner for loop, where I check if words[i] and words[j] are not null, and then proceed with assining value to second word in pair.
In the last part I check if words[i] is equal to reversed words[j]. If there is a match I assign null value to both words, if not increment i.
package com.codegym.task.task22.task2207;
import java.util.LinkedList;
import java.util.List;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.io.IOException;
/*
Inverted words
*/
public class Solution {
public static List<Pair> result = new LinkedList<>();
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
reader.close();
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
StringBuilder sb = new StringBuilder();
while(line != null) {
sb.append(line);
line = br.readLine();
}
br.close();
for (int index = 0; index < sb.length(); index++) {
if (sb.charAt(index) == '\n') {
sb.setCharAt(index, ' ');
}
}
String[] words = sb.toString().split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i] != null) {
String word1 = words[i];
for (int j = i + 1; j < words.length; j++) {
if (words[j] != null && words[i] != null) {
StringBuilder builder = new StringBuilder();
builder.append(words[j]).reverse();
String word2 = builder.toString();
if (word1.equals(word2)) {
StringBuilder test = new StringBuilder();
test.append(word2);
Pair pair = new Pair();
pair.first = word1;
pair.second = test.reverse().toString();
result.add(pair);
test.setLength(0);
builder.setLength(0);
words[i] = null;
words[j] = null;
}
}
}
}
}
}
public static class Pair {
String first;
String second;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
return second != null ? second.equals(pair.second) : pair.second == null;
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
@Override
public String toString() {
return first == null && second == null ? "" :
first == null ? second :
second == null ? first :
first.compareTo(second) < 0 ? first + " " + second : second + " " + first;
}
}
}