PRASHNIKAप्रश्निका
Back to the paper

A class Capital has been defined to check whether a sentence has words beginning with a capital…

Computer Science201810 marksProgram
A class Capital has been defined to check whether a sentence has words beginning with a capital letter or not. Some of the members of the class are given below: Class name : Capital Data member/instance variable: sent : to store a sentence freq : stores the frequency of words beginning with a capital letter Member functions/methods: Capital( ) : default constructor void input( ) : to accept the sentence boolean isCap(String w) : checks and returns true if word begins with a capital letter, otherwise returns false void display( ) : displays the sentence along with the frequency of the words beginning with a capital letter Specify the class Capital, giving the details of the constructor( ), void input( ), boolean isCap(String) and void display( ). Define the main( ) function to create an object and call the functions accordingly to enable the task.

Answer

Answer

AI
import java.util.Scanner;
import java.util.StringTokenizer;

class Capital
{
    String sent;
    int freq;

    Capital()
    {
        sent = "";
        freq = 0;
    }

    void input()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        sent = sc.nextLine();
    }

    boolean isCap(String w)
    {
        char ch = w.charAt(0);
        if (ch >= 'A' && ch <= 'Z')
            return true;
        else
            return false;
    }

    void display()
    {
        StringTokenizer st = new StringTokenizer(sent, " ,.");
        freq = 0;
        while (st.hasMoreTokens())
        {
            String w = st.nextToken();
            if (isCap(w))
                freq++;
        }
        System.out.println("Sentence : " + sent);
        System.out.println("Frequency of words beginning with a capital letter : " + freq);
    }

    public static void main(String args[])
    {
        Capital ob = new Capital();
        ob.input();
        ob.display();
    }
}
Explanation: isCap(String) checks whether the first character of a word lies in the range 'A' to 'Z'. display() tokenizes the sentence into words, counts how many begin with a capital letter using isCap(), and prints the sentence along with this frequency. Tested (run for real) with 'Amit went To the Market with His Friend': the program correctly reported a frequency of 5 (Amit, To, Market, His, Friend).
Objects

From ISC 2018 Computer Science Paper 1, question 9.