This program was compiled and checked on Bluej
This program accepts a sentence from the user and displays the longest word and its length.
SOURCE CODE :
import java.io.*;//package
class longestword//class name longest word
{
static String str,word;
static int l,b,a,counter,l2;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(read);
longestword()//default constructor
{
l=l2=0;
str="";
b=0;
counter=0;
}
void inputword()throws IOException
{
System.out.println("Enter a sentence.....");
str=br.readLine();//store the sentence in str
l=str.length();//store the length of the sentence in l
str=str+" ";//add blank space to the sentece
}
void compute()throws IOException
{
for(a=0;a<=l;a++)
{
if(str.charAt(a)==' ')//to extract each word
{
l2=(str.substring(b,a)).length();//to store the length of a word
if(l2>=counter)//compare length
{
word=str.substring(b,a);//to store the longest word
counter=l2;//store the frequency of the longest word
}
b=a+1;
l2=0;
}
}
}
void display()throws IOException
{
System.out.println("the longest word int the given sentence is..."+word);//to display the longest word
System.out.println("frequency of the longest word is..."+counter);//display the frequency of the longest word
}
public static void main(String args[])throws IOException
{
longestword ob= new longestword();//creating object
ob.inputword();
ob.compute();
ob.display();
}
}
Output:

This program was compiled and checked on Bluej
This program accepts a sentence from the user and displays the longest word and its length.
SOURCE CODE :
import java.io.*;//package
class longestword//class name longest word
{
static String str,word;
static int l,b,a,counter,l2;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(read);
longestword()//default constructor
{
l=l2=0;
str="";
b=0;
counter=0;
}
void inputword()throws IOException
{
System.out.println("Enter a sentence.....");
str=br.readLine();//store the sentence in str
l=str.length();//store the length of the sentence in l
str=str+" ";//add blank space to the sentece
}
void compute()throws IOException
{
for(a=0;a<=l;a++)
{
if(str.charAt(a)==' ')//to extract each word
{
l2=(str.substring(b,a)).length();//to store the length of a word
if(l2>=counter)//compare length
{
word=str.substring(b,a);//to store the longest word
counter=l2;//store the frequency of the longest word
}
b=a+1;
l2=0;
}
}
}
void display()throws IOException
{
System.out.println("the longest word int the given sentence is..."+word);//to display the longest word
System.out.println("frequency of the longest word is..."+counter);//display the frequency of the longest word
}
public static void main(String args[])throws IOException
{
longestword ob= new longestword();//creating object
ob.inputword();
ob.compute();
ob.display();
}
}
Output:
This program was compiled and checked on Bluej
No comments:
Post a Comment