Computer Science, asked by pallavipbenni206, 2 months ago

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 anindyaadhikari13
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:

  1. Accepting the sentence.
  2. Split the sentence into words using split() function and store the words in array.
  3. Assume that the first word in the array is the largest word.
  4. Loop through all the elements in the array.
  5. Check if any word is greater than the largest word. If true, store that word in the largest word variable.
  6. Display the largest word along with its length.
Attachments:
Similar questions