Class 11 Assignment 10 (Prac)
Class 11 Assignment 10 (Prac)
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 a 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 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
void display() : 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.
import java.util.*;
class TheString
{
String str;
int len;
int wordCount;
int cons;
public TheString()
{
str=new String();
len=0;
wordCount=0;
cons=0;
}
public TheString(String ds)
{
str=ds;
if(str. length()> 100)
str=str. substring(0, 101);
len=str.length();
wordCount=0;
cons=0;
}
public void countFreq()
{
int i;
for(i=0;i<len;i++)
{
char ch=str.charAt(i);
if(ch==' ')
wordCount++;
ch=Character.toUpperCase(ch);
switch(ch)
{
case 'A':
case'E':
case 'I':
case 'O':
case 'U':
break;
default:
if(ch>='A' && ch<='Z')
cons++;
}
}
if(len>0)
wordCount++;
}
public void display()
{
System. out.println("Original String :"+str);
System.out.println("Number of words: "+wordCount);
System.out.println("Number of consonants:"+cons);
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the string:");
String s=sc.nextLine();
TheString obj=new TheString(s);
obj.countFreq();
obj.display();
}
}