- #1
anyonebutangel
- 40
- 5
- Homework Statement
- java STRING program
- Relevant Equations
- no equations
Summary:: I'm having problem with this source code.we need to find the frequency of the number of words beginning with an UPPERCASE Alphabet in a sentence.
The data members and member method must be according to the question given in the document.
though i could compile it but it's giving runtime error for STRING INDEX OUT OF BOUNDS EXCEPTION. I hope someone can help me point out where I'm missing the error.
The data members and member method must be according to the question given in the document.
though i could compile it but it's giving runtime error for STRING INDEX OUT OF BOUNDS EXCEPTION. I hope someone can help me point out where I'm missing the error.
Java:
.
/*Question:
A class Capital has been defined to check wether a sentence has words beginning with a capital latter or not.
Some of the members of the class are given below:
Class name : Capital
Data members/instance variables :
sent : to store the 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 the word begins with a capital letter .
Specify the class Capital giving details of the constructor, void input(),Boolean isCap(String w) and void display().Define the main() function to create an object and call the function accordingly to enable the task.
*/
import java.io.*; //importing package
class Capital
{
String sent; //global data members
int freq,l;
Capital() //constructor
{
sent="";
freq=0;
}
void input()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //creating object "br" for input
System.out.println("ENTER THE SENTENCE");
sent=br.readLine();
l=sent.length(); //variable "l" stores the length of the string
}
boolean isCap(String w) //boolean function to check if word begins with an uppercase alphabet
{
if(w.charAt(0)>='A'||w.charAt(0)<='Z')
return(true);
else
return(false);
}
void display()
{
int j=0;
System.out.println("THE SENTENCE ENTERED IS:"+sent);
for(int i=sent.indexOf(' ');i<l;i++)
{
while(sent.charAt(i)==' ') //while loop to count the frequemcy of words beginning with capital letters
{
if(isCap(sent.substring(j,i))==true)
{
freq++;
j=i+1;
}
}
}
System.out.println("THE NUMBER OF WORDS BEGINNING WITH UPPERCASE ALPHABET IS:"+freq);
} //end of display()
public static void main(String args[])throws IOException
{
Capital ob=new Capital();
ob.input();
ob.display();
} //end of main()
} //end of class
Attachments
Last edited by a moderator: