I am writing the following code to display the longest word in a sentence and there are bugs which I have no idea how to solve this. Please help me.
Input st = aaaa bbbb ccccc ddd eee ffff aaaa bbbb ccccc ddd eee ffff aaaa bbbb ccccc ddd eee ffff
Output = remaining: ddd eee ffff
If it is a shorter sentence, the code works fine.
Input st = aaaa bbbb ccccc ddd eee ffff aaaa bbbb
Output = longest: ccccc
public static void charNum(String st) { String first_word; int word_length; String longest_word = ""; int temp_wordcount = 0; String remaining_words = ""; for (int i = 0; i < st.length(); i++) { word_length = st.indexOf(' '); if (word_length<0) { break; } first_word = st.substring(0, word_length); remaining_words = st.substring(word_length+1, st.length()); if (word_length > temp_wordcount) { longest_word = first_word; } temp_wordcount = longest_word.length(); st = st.substring(word_length+1); } if (remaining_words.length() > longest_word.length()) { System.out.println("remaining: " + remaining_words); } else { System.out.println("longest: " +longest_word); }