icse-promo

Question

 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:
Classname:TheString
Data members /instance variables:
str:to store a string
len: integer to store the length of the string
wordcount:integer to store number of words
cons:integer to store number of consonants
Member functions/methods:
TheString():default constructor to initialize the data members
TheString(String ds):parameterized constructor to assign str=ds
void countFreq():to count the number of words and the number of consonants and store them in wordcount and cons respectively
voidDisplay(): to display the original string,along with the number of words and the number of consonants
Specify the class TheString giving the 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

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner; 
public class TheString
{
    String str;
    int len,wordcount,cons;
    TheString()
    {
        str="";
        wordcount=0;
        cons=0;
    }

    TheString(String ds)
    {
        str=ds+" ";
        len=str.length();
        cons=0;
        wordcount=0;
        
    }
    
    void countFreq()
    {
        char ch=' ';
        str=str.toLowerCase();
        for(int i=0;i< len;i++)
        {
            ch=str.charAt(i);
            if(ch==' ')
            {
                wordcount++;
            }

            else
            {
                if(ch!='a'&&ch!='e'&&ch!='i'&&ch!='o'&&ch!='u')
                {
                    cons++;
                }
            }

        }
    }
    
    void Display()
    {
        System.out.println("Number of words="+wordcount);
        System.out.println("Number of consonants="+cons);
    }
    
    public static void main()
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("ENTER A SENTENCE WITH CHARACTER NOT MORE THAN 100");
        String sen=sc.nextLine();
        TheString ob1=new TheString(sen);
        ob1.countFreq();
        ob1.Display();
    }
}



				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *