title: Using recursion to find the longest word in a sentence (Java)
body: <p>For an assignment, I am supposed to find the longest word in a sentence using recursion. I wrote a method that takes the first two words of the sentence, compares them, and then takes the longer of the two and compares that to the next word in the rest of the sentence. My logic checks out, but the method does not work correctly. I think there is a fluke that takes out spaces, and that is why it is not working.</p>
  
  <pre><code>public static String longestWord(String sentence)
  {
      if (sentence.indexOf(' ') == -1) {      // IF sentence only has one word
          return sentence;
      }
  
      String word1 =(sentence.indexOf(" ") != -1)? sentence.substring(0, sentence.indexOf(" ")):
                                                      sentence.substring(0);
      String temp = sentence.substring(sentence.indexOf(" ")+1);
  
  
      String word2 = null;
      String rest = null;
      if (sentence.indexOf(" ") != -1)    {
       word2 = (temp.indexOf(" ") != -1)? temp.substring(0, temp.indexOf(" ")+1):
                                              temp.substring(0);
       rest = temp.substring(temp.indexOf(" ")+1);
      }
  
  
      if (word1.length() &gt; word2.length()) {
          return longestWord(word1 + rest);
  
      }
  
      if (word2.length() &gt; word1.length())  {
          return longestWord(word2 + rest);
  
      }
  
      return sentence;
  
  
  }
  </code></pre>