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 accepts(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.
import java.util.*;
class Frequency
{
String text;
int countan,countand,len;
private frequency()
{
text="";
countan=0;
countand=0;
len=0;
}
private void accept(String n)
{
text=n;
StringTokenizer stk=new StringTokenizer(text," ");
while(stk.hasMoreTokens())
{
String s=stk.nextToken();
checkandfreq(s);
checkanfreq(s);
}
}
private void checkandfreq(String s)
{
if(s.equals("and"))
countand++;
}
private void checkanfreq(String s)
{
if(s.equals("an"))
countan++;
}
private void dsiplay()
{
System.out.println("The no. of an :"+countan);
System.out.println("The no. of and :"+countand);
}
public static void main(String str[])
{
Scanner sc=new Scanner(System.in);
Frequency ob=new Frequency();
System.out.println("Enter the Sentence");
String n=sc.nextLine();
ob.accept(n);
ob.dsiplay();
}
}
No comments:
Post a Comment