Frequency Program ISC Computer Science 2011 Theory

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 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 lowercase.
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 the methods accordingly to enable the task.

import java.util.Scanner;
class Frequency{
    String text;
    int countAnd;
    int countAn;
    int len;
    public Frequency(){
        text = "";
        countAnd = 0;
        countAn = 0;
        len = 0;
    }
    public void accept(String n){
        text = n;
        len = text.length();
    }
    public void checkAndFreq(){
        String word = "";
        for(int i = 0; i < len; i++){
            char ch = text.charAt(i);
            if(Character.isLetter(ch))
                word += ch;
            else{
                if(word.equals("and"))
                    countAnd++;
                word = "";
            }
        }
        if(word.equals("and"))
            countAnd++;
    }
    public void checkAnFreq(){
        String word = "";
        for(int i = 0; i < len; i++){
            char ch = text.charAt(i);
            if(Character.isLetter(ch))
                word += ch;
            else{
                if(word.equals("an"))
                    countAn++;
                word = "";
            }
        }
        if(word.equals("an"))
            countAn++;
    }
    public void display(){
        System.out.println("Frequency of and: " + countAnd);
        System.out.println("Frequency of an: " + countAn);
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the sentence: ");
        String s = in.nextLine().toLowerCase();
        Frequency obj = new Frequency();
        obj.accept(s);
        obj.checkAndFreq();
        obj.checkAnFreq();
        obj.display();
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory