My code works for the task example.
I would have expected it to fail:
All words passed to the getLine method must be included in the resulting string, if possible.
as if there is a word that doesn't fit in with the word chain, I would have an infinite loop.
I especially don't understand why it's failing:
The getLine method must return an empty string (an empty StringBuilder) if it is not passed arguments (words)
package com.codegym.task.task22.task2209;
/*
Make a word chain
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Solution {
public static void main(String[] args) throws Exception{
// ...
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
String chain = bufferedReader.readLine();
String[] words = chain.split(" ");
StringBuilder result = getLine(words);
System.out.println(result.toString());
}
public static StringBuilder getLine(String... words) {
StringBuilder chain = new StringBuilder("");
if (words == null) return chain;
ArrayList<String> wordList = new ArrayList<>();
wordList.add(words[0]);
while (wordList.size() < words.length){
for (int i = 0; i < wordList.size(); i++){
for (int j = 1; j < words.length; j++){
if (wordList.contains(words[j])) continue;
if (checkEndings(wordList.get(i), words[j]))
wordList.add(i, words[j]);
else if (checkEndings(words[j], wordList.get(i)))
wordList.add(i+1, words[j]);
}
}
}
for (String s : wordList)
chain.append(s).append(" ");
chain.deleteCharAt(chain.length()-1);
return chain;
}
public static boolean checkEndings(String a, String b){
return String.valueOf(a.charAt(0)).equalsIgnoreCase(String.valueOf(b.charAt(b.length()-1))) ;
}
}