Write a program to input a piece of text consisting of
sentences terminated by either ‘.’ or ‘!’ or ‘?’. The program should output the
mean and standard deviation of the lengths of sentences (measured in words).
Each word is separated by a blank space.
Mean => x’ = n
å x i
i= 1
---------------
n
where x i is the length of the ith
sentence and n is the total number of sentences.
Standard Deviation
n
s
= Ö
å(
xi – x’)2
i=1
-----------------
n
( Assume a maximum
of 10 sentences ) . Test your program for the following input :
HELLO!HOW ARE YOU?HOPE EVERYTHING IS FINE.BEST OF LUCK.
Answer
2.
class Q2_1998
{
//Data members
private String para;
private int len;
private String
[]sentences;
private int nos;
private int
[]lensent;
//Constructor
public Q2_1998(String
par)
{
para=par+"
";
len =
para.length();
sentences=new
String[10];
nos=0;
lensent=new
int[10];
int i;
//Initilizing
array for storing length of sentences
for(i=0;i<10;i++)
lensent[i]=0;
}
//method to extract
sentences
public void Extract()
{
para=para.toUpperCase();
String
word="",sent="";
int i;
char letr;
for(i=0;i<len;i++)
{
letr=para.charAt(i);
if(letr!='
')
word+=letr;
if(letr=='
')
{
sent+=word;
sent+=" ";
word="";
}
if(letr=='.'||letr=='!'||letr=='?')
{
sent+=word;
sent+=" ";
i++;//so as not to pick up the blank after the ., ? or !
sentences[nos]=sent;
sent="";
nos++;
word="";
}
}
}
//method to find
length of sentences
public void
findlength()
{
int i,j;
char letter;
Extract();
for(i=0;i<nos;i++)
{
for(j=0;j<sentences[i].length();j++)
{
letter=sentences[i].charAt(j);
if(letter==' ')
lensent[i]++;
}
}
}
//method to find
standard deviation
public void
standarddeviation()
{
int i,sum=0;
double
mean,std=0;
findlength();
//Finding total
length of all sentences
for(i=0;i<nos;i++)
sum+=lensent[i];
mean=sum/nos;
//Finding
standard deviation
for(i=0;i<nos;i++)
{
std=Math.sqrt((Math.pow((lensent[i]-std),2))/nos);
System.out.println(sentences[i]+"\t\t\t deviates from mean by
\t\t"+ std);
}
}
}
import java.io.*;
class Q2_1998main
{
public static void
main(String args[])
throws IOException
{
BufferedReader
br=new BufferedReader(new InputStreamReader(System.in));
String para;
System.out.println("Enter a paragraph ");
para=br.readLine();
Q2_1998 obj=
new Q2_1998(para);
obj.standarddeviation();
}
}
Output
Enter a paragraph
HELLO! HOW ARE YOU? HOPE EVERYTHING IS FINE. BEST OF LUCK.
HELLO! deviates from mean by 0.5
HOW ARE YOU? deviates from mean by 1.25
HOPE EVERYTHING IS FINE. deviates from mean by 1.375
BEST OF LUCK. deviates from mean by 0.8125