So far I tried different combinations of words, including a combination corresponding to the 'if possible' part of the 6th condition.
Everything seems to work perfectly fine, but I still don't get the last 2 conditions.
One of my theories is that my getLastWord method has an if condition with a return statement in its body.
The validator might not accept it, because of the possibility of not returning the actual last word.
What do you think, guys?
Thanks!
package com.codegym.task.task22.task2209;
/*
Make a word chain
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class Solution {
public static void main(String[] args) throws IOException {
// ...
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader fileReader = new BufferedReader(new FileReader(reader.readLine()));
List<String> words = new ArrayList<>();
while (fileReader.ready()) {
words.addAll(Arrays.asList(fileReader.readLine().split(" ")));
}
String[] wordsArr = new String[words.size()];
for (int i = 0; i < words.size(); i++) {
wordsArr[i] = words.get(i);
}
StringBuilder result = getLine(wordsArr);
System.out.println(result.toString());
}
public static StringBuilder getLine(String... words) {
if (words.length == 0) return new StringBuilder();
List<String> wordsList = new ArrayList<>(Arrays.asList(words));
String lastWord = getLastWord(words);
StringBuilder result = new StringBuilder(getLastWord(words));
wordsList.remove(lastWord);
while (true) {
boolean match = false;
for (int i = 0; i < wordsList.size(); i++) {
String currentWord = wordsList.get(i);
if (currentWord.charAt(currentWord.length() - 1) == result.toString().toLowerCase().charAt(0)) {
result = new StringBuilder(currentWord + " " + result);
wordsList.remove(currentWord);
match = true;
}
}
if (!match)
break;
}
return result;
}
public static String getLastWord(String... words) {
boolean match = false;
String currentWord = "";
for (int i = 0; i < words.length; i++) {
currentWord = words[i];
for (int j = 0; j < words.length; j++) {
if (i != j && currentWord.charAt(currentWord.length() - 1) == words[j].toLowerCase().charAt(0)) {
match=true;
}
}
if (!match) return currentWord;
match = false;
}
return currentWord;
}
}