Write
a BlueJ Program to enter a sentence and find the longest and shortest words from the
sentence. In both cases the first word (longest or shortest) will be displayed.
import java.io.*;
class
Words
{
String str1,str2,maxs,mins;
int max,min;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
private void show() throws Exception
{
System.out.print("\nEnter the
sentence:");
str1=br.readLine().trim();
str1=str1+" ";
max=0;
min=str1.length();
while(true)
{
int i=str1.indexOf(' ');
if (i<0 o:p="">0>
break;
str2=str1.substring(0,i);
str1=str1.substring(i+1);
if(str2.length()>max)
{
max=str2.length();
maxs=str2;
}
else if(str2.length()
{
min=str2.length();
mins=str2;
}
}
System.out.println("Longest
Word Is:"+maxs);
System.out.println("Shortest
Word Is:"+mins);
}
public static void main(String args[])
throws Exception
{
Words ob=new Words ();
ob.show();
}
}
Sample Input and Output
Enter the sentence: I am a proud Indian
Longest Word Is: Indian
Shortest Word Is: a
No comments:
Post a Comment