Write a program in Java to enter a String/Sentence and display the longest word
and the length of the longest word present in the String.
Sample Input: "TATA FOOTBALL ACADEMY WILL PLAY
AGAINST MOHAN BAGAN"
Sample Output: The longest word: FOOTBALL: The length of the word: 8
Answers
Answered by
5
Answer:
This is the required Java program for the question.
import java.util.*;
public class LargestWord {
public static void main(String args[]) {
String w;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a sentence: ");
String a[]=sc.nextLine().split(" ");
w="";
for(String i:a) {
if(w.length()<i.length())
w=i;
}
System.out.println("Largest Word: "+w);
System.out.println("Length: "+w.length());
sc.close();
}
}
Algorithm:
- Accepting the sentence.
- Split the sentence into words using split() function and store the words in array.
- Assume that the first word in the array is the largest word.
- Loop through all the elements in the array.
- Check if any word is greater than the largest word. If true, store that word in the largest word variable.
- Display the largest word along with its length.
Attachments:
Similar questions