This Java program finds and prints the longest word in a given sentence. It uses a Scanner to read input, iterates through the characters of the sentence to extract words, and compares their lengths to determine the longest one. The program also handles ties by comparing the words lexicographically.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
6 views2 pages
Longest Word
This Java program finds and prints the longest word in a given sentence. It uses a Scanner to read input, iterates through the characters of the sentence to extract words, and compares their lengths to determine the longest one. The program also handles ties by comparing the words lexicographically.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2
Program to print the longest word in the sentence
import java.util.*; //Importing packages
import java.io.*;
import java.lang.*;
public class longest_word //declaring class
{ //opening braces of class
public static void main(String args[]) //declaring main method
{ //opening braces of main method
String s,w="",l=""; //temporary variables
char c;
Scanner pa = new Scanner(System.in); //declaring Scanner class
System.out.println("Enter a sentence");
s=pa.nextLine()+" ";; //Store the Sentence
int m=0; //to store the maximum length
for(int i=0;i<s.length();i++)
c = s.charAt(i); //to Store character at i
if(c!=' ') //To extract the word
w=w+c; //To store the word
else
if(w.length() > m) //To check word length with maximum length
m = w.length(); //to store the word length in maximum
l = w; //to store the longest word
else if(w.length()==m) //to check if the world length is equal to maximum length
if(w.compareTo(l) > 0) //compare word with longest word
{
l = w; //to store the longest word
w=""; //to empty the word
System.out.println("Longest word is "+l); //Print the longest word in the sentence
} //closing braces of main method
} //closing braces of class
VARIABLE DATA TYPE FUNCTION
s String To store the Sentence c Character To store the character at an index i Integer To Extract a word from the sentence w String To Store the word l String To Store the Longest word