502,647 views
33 votes
33 votes
Write a small JAVA method to return the longest word in a string using for, do while, or while loops. NO ARRAYS!!!!

- user enters sentence
- method returns longest word

(for example: he plays an interesting sport.
returns interesting)

User Rajnish Suryavanshi
by
3.0k points

1 Answer

21 votes
21 votes

Answer:

public static String longestWord(String input) {

// split the input string into an array of words

String[] words = input.split(" ");

// initialize the longest word to be the first word in the array

String longestWord = words[0];

// initialize the index of the current word to 1

int i = 1;

// loop through the remaining words in the array

while (i < words.length) {

// if the current word is longer than the longest word,

// update the longest word to be the current word

if (words[i].length() > longestWord.length()) {

longestWord = words[i];

}

// move to the next word in the array

i++;

}

// return the longest word

return longestWord;

}

Step-by-step explanation:

To use this method, you can call it with a string argument, like this:

String sentence = "he plays an interesting sport";

String longestWord = longestWord(sentence);

// the variable 'longestWord' should now be "interesting"

Note that this method does not use arrays, as requested in the question. Instead, it uses a while loop to iterate over the words in the input string.

User Alex Zhevzhik
by
2.2k points