Question
Input a sentence from the user and count the number of times,the words “an” and “and” are present in
the sentence. Design a class Frequency using the description given below:
Class name:Frequency
Data Members/ variables :
text:stores the sentence
countand: to store the frequency of the word “and”
countan: to store the frequency of the word “an”
len: stores the length of the string
Member functions / methods:
Frequency( ) :constructor to initialize the instance variables
void accept(String n):to assign n to text,where the value of the parameter n should be in lower case.
void checkandfreq( ):to count the frequency of “and”
void checkanfreq( ):to count the frequency of “an”
void display( ):to display the number of”and” and “an” with appropriate messages.
Specify the class Frequency giving details of the constructor( ), void accept(String),void checkandfreq( ),void checkanfreq( ) and void display( ).Also define the main( ) function to create an object and call methods accordingly to enable the task.
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class Frequency
{
String text;
int countand,countan,len;
public Frequency()
{
text="";
countand=0;
countan=0;
}
public void accept(String n)
{
text=n;
if(text.charAt(text.length()-1)!='.')
{
text=text+'.';
}
len=text.length();
}
public void checkandfreq()
{
int pos=0,i=0;
char ch=' ';
String b="";
for(i=0;i< len;i++)
{
ch=text.charAt(i);
if(ch==' '||ch=='.')
{
b=text.substring(pos,i);
if(b.equals("and")==true)
{
countand++;
}
pos=i+1;
}
}
}
public void checkanfreq()
{
int pos=0,i=0;
char ch=' ';
String b="";
for(i=0;i< len;i++)
{
ch=text.charAt(i);
if(ch==' '||ch=='.')
{
b=text.substring(pos,i);
if(b.equals("an")==true)
{
countan++;
}
pos=i+1;
}
}
}
public void display()
{
System.out.println("Number of and's="+countand);
System.out.println("Number of an's="+countan);
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence in Lowercase");
String n=sc.nextLine();
Frequency ob1=new Frequency();
ob1.accept(n);
ob1.checkandfreq();
ob1.checkanfreq();
ob1.display();
}
}