Count Consonants ISC Computer Science 2015 Theory

A class TheString accepts a string of a maximum of 100 characters with only one blank space between the words.

Some of the members of the class are as follows:

Class name: TheString

Data members/instance variables:
str: to store the string
len: integer to store the length of the string
wordCount: integer to store the number of words
cons: integer to store the number of consonants

Member functions/methods:
TheString(): default constructor to initialize the data members
TheString(String s): parameterized constructor to assign str = s
void countFreq(): to count the number of words and the number of consonants and store them in wordCount and cons respectively
void display(): to display the original string, along with the number of words and the number of consonants

Specify the class TheString giving details of the constructors, void countFreq() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.

import java.util.Scanner;
import java.util.StringTokenizer;
class TheString{
    String str;
    int len;
    int wordCount;
    int cons;
    public TheString(){
        str = new String();
        len = 0;
        wordCount = 0;
        cons = 0;
    }
    public TheString(String s){
        str = new String(s);
        len = str.length();
        wordCount = 0;
        cons = 0;
    }
    public void countFreq(){
        str = str.toLowerCase();
        StringTokenizer st = new StringTokenizer(str);
        wordCount = st.countTokens();
        for(int i = 0; i < len; i++){
            char ch = str.charAt(i);
            if(Character.isLetter(ch) && "aeiou".indexOf(ch) == -1)
                cons++;
        }
    }
    public void display(){
        System.out.println("Original string: " + str);
        countFreq();
        System.out.println("Number of words: " + wordCount);
        System.out.println("Number of consonants: " + cons);
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the string: ");
        String s = in.nextLine();
        TheString obj = new TheString(s);
        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