Shortest Word In A Sentence | Write a program in Java to find the shortest word in a sentence. | ISC Computer Science | ICSE Computer Application
Algorithm
- Start
- in=""
- word=""
- shortest=""
- Print "Enter a sentence"
- Read in
- in=in+" "
- shortest=in
- If in.equals("")==false, go to step 10 or else go to step 15
- word=in.substring(0, in.indexOf(' '))
- If word.length()<shortest.length(), go to step 12 or else go to step 13
- shortest=word
- in=in.substring(in.indexOf(' ')+1, in.length())
- Go to step 9
- Print "The shortest word is "+shortest
- Stop
Program
Buffered Reader
import java.io.*;
class Shortest
{
String in, word="", shortest="";
void accept() throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter a sentence");
in=br.readLine();
in=in+" ";
shortest=in;
}
void shortest()
{
while(in.equals("")==false)
{
word=in.substring(0, in.indexOf(' '));
if(word.length()<shortest.length())
{
shortest=word;
}
in=in.substring(in.indexOf(' ')+1, in.length());
}
}
void display()
{
System.out.println("The shortest word is "+shortest);
}
void main() throws IOException
{
accept();
shortest();
display();
}
}
Scanner
import java.util.*;
class Shortest
{
String in, word="", shortest="";
void accept()
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter a sentence");
in=sc.nextLine();
in=in+" ";
shortest=in;
}
void shortest()
{
while(in.equals("")==false)
{
word=in.substring(0, in.indexOf(' '));
if(word.length()<shortest.length())
{
shortest=word;
}
in=in.substring(in.indexOf(' ')+1, in.length());
}
}
void display()
{
System.out.println("The shortest word is "+shortest);
}
void main()
{
accept();
shortest();
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 | shortest | To store the shortest 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 shortest 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