Longest Word In A Sentence | Write a Program In Java to Find the Longest Word In A Sentence.| ISC Computer Science | ICSE Computer Applications
In this program, we write a program in java accept a sentence from the user and print the longest word in the sentence.
Methods used:
str.length(), str.substring(), str.indexOf().
Algorithm
- Start
- in=""
- word=""
- longest=""
- Print "Enter a sentence"
- Read in
- in=in+" "
- If in.equals("")==false, go to step 9 or else go to step 14
- word=in.substring(0, in.indexOf(' '))
- If word.length()>longest.length(), go to step 11 or else go to step 12
- longest=word
- in=in.substring(in.indexOf(' ')+1, in.length())
- Go to step 8
- Print "The longest word is "+longest
- Stop
Program
Buffered Reader
import java.io.*;
class Longest
{
String in, word="", longest="";
void accept() throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter a sentence");
in=br.readLine();
in=in+" ";
}
void longest()
{
while(in.equals("")==false)
{
word=in.substring(0, in.indexOf(' '));
if(word.length()>longest.length())
{
longest=word;
}
in=in.substring(in.indexOf(' ')+1, in.length());
}
}
void display()
{
System.out.println("The longest word is "+longest);
}
void main() throws IOException
{
accept();
longest();
display();
}
}
Scanner
import java.util.*;
class Longest
{
String in, word="", longest="";
void accept()
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter a sentence");
in=sc.nextLine();
in=in+" ";
}
void longest()
{
while(in.equals("")==false)
{
word=in.substring(0, in.indexOf(' '));
if(word.length()>longest.length())
{
longest=word;
}
in=in.substring(in.indexOf(' ')+1, in.length());
}
}
void display()
{
System.out.println("The longest word is "+longest);
}
void main()
{
accept();
longest();
display();
}
}
Documentation
Variable Description
Data Type | Variable Name | Description |
String | in | To store the sentence from the user |
String | word | To store a word from the sentence |
String | longest | To store the longest word of the sentence |
Method Description
Return Type | Method Name | Description |
void | accept() | To accept a sentence from the user |
void | longest() | To find the longest word in a sentence |
void | display() | To display the longest word |
void | main() | To act as an entry gateway for the compiler. |
Output
Share with all ISC Computer Science Students you know.
Comment below with all your program requests and blog suggestions.
Follow us on social media by clicking on these links.
Instagram : @ISCJavaCode
Twitter: @ISCJavaCode
Quora: ISC Java Code
Reddit: @ISCJavaCode
Stay Healthy
Stay Happy
Stay Helpful
Comments
Post a Comment