Problem with this Java string program

In summary, the class Capital has been defined to check wether a sentence has words beginning with a capital latter or not. The member functions/methods are: Capital() //constructorvoid input() : to accept the sentenceBoolean isCap(String w) : checks and returns true if the word begins with a capital letter .
  • #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.

cap.PNG


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

  • Capital.txt
    2 KB · Views: 307
Last edited by a moderator:
Physics news on Phys.org
  • #2
That means you have tried to access a character that is beyond the end of a string.

If you want anyone to look at your code please post it inside [code=java]...[/code] tags.
 
  • #3
pbuk said:
That means you have tried to access a character that is beyond the end of a string.

If you want anyone to look at your code please post it inside [code=java]...[/code] tags.
I've posted it as a text document both question and the code
 
  • #4
pbuk said:
That means you have tried to access a character that is beyond the end of a string.

If you want anyone to look at your code please post it inside [code=java]...[/code] tags.
I've posted it as a text document both question and the code
will that do?
 
Last edited by a moderator:
  • #5
Splitting a string into substrings based on the occurence of a particular character is a common task for which there is a library function:
Java:
   String[] words = sent.split(' ');
This will probably solve your indexing error, because you will then only need to check the first character of each word.

You can replace isCap with
Java:
public boolean isCap(String w)
{
   return w.charAt(0) >= 'A' && w.charAt(0) <= 'Z';
}
or, even better because it correctly handles things like 'Å',
Java:
public boolean isCap(String w)
{
   return Character.isUpperCase(w.charAt(0));
}
 
  • #6
anyonebutangel said:
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.

View attachment 268979
pasmith said:
Splitting a string into substrings based on the occurence of a particular character is a common task for which there is a library function:
Java:
   String[] words = sent.split(' ');
This will probably solve your indexing error, because you will then only need to check the first character of each word.

You can replace isCap with
Java:
public boolean isCap(String w)
{
   return w.charAt(0) >= 'A' && w.charAt(0) <= 'Z';
}
or, even better because it correctly handles things like 'Å',
Java:
public boolean isCap(String w)
{
   return Character.isUpperCase(w.charAt(0));
}
this program is a part of school project so I'm supposed to solve this in accordance to the syllabus prescribed and as i mentioned in the thread it must be strictly in accordance to the question that preceeds the code we have to use the same member method and data members and library functions are still not included in the syllabus..we cannot manipulate the names of method.Kindly help me point out why is it giving the STRING INDEX OUT OF BOUNDS EXCEPTION.
 
  • #7
What if the string has no spaces? What does the index function return?
 
  • #8
jedishrfu said:
What if the string has no spaces? What does the index function return?
according to the question we have to assume that.
if it was not for the question,I agree with you that this point about white space character should be considered.
 
  • #9
The error message tells you that something is wrong when you call the substring method in line 52. Try inserting the following line before line 52:
Java:
        System.out.println("j = " + j + ", i = " + i);
which will show you what is wrong, then work out how i and j have acquired these values.
 
  • #10
My post was a hint as the index function returns a -1 when there are no spaces and so youve set your i variable to -1 with the possible and likely subsequent fail you observe.

You should test for it and decide what to do.
 
  • #11
Let's take a closer clook as display().
Java:
. 
void display()
{
   int j=0;

This really needs a name which describes its purpose.

Java:
   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;

This is your problem. As written, the for loop starts at a point where sent.charAt(i) is a space. Which means that the condition in the while loop is always true. Which means that j will eventually exceed i, which is probably what substring is objecting to.

A while loop where the condition does not depend on a variable modified by the loop and which has no explicit break statement is asking for trouble.

I can't work out what your loop is supposed to be doing, because your intended algorithm is not clear to me.

I would suggest this: Have a variable which stores the position of the first character of the current word (and call it something meaningful, such as wordStart. If you don't have a current word yet, set this to something obviously invalid like -1.

A word begins when you don't have a current word and you reach a character which is not a space.
A word ends when you reach a character which is either a space or the last character in the string.

You don't need to track the end of the word; all you need to pass to isCap is the "word" consisting of the first letter of the current word (ie. sent.substring(wordStart,wordStart)).

Start at the beginning of the string and work through until you reach the end. Whenever you reach the end of a word, process that word and then set wordStart = -1.
 
  • Like
Likes sbrothy
  • #12
pasmith said:
Splitting a string into substrings based on the occurence of a particular character is a common task for which there is a library function:
Java:
   String[] words = sent.split(' ');
This will probably solve your indexing error, because you will then only need to check the first character of each word.

You can replace isCap with
Java:
public boolean isCap(String w)
{
   return w.charAt(0) >= 'A' && w.charAt(0) <= 'Z';
}
or, even better because it correctly handles things like 'Å',
Java:
public boolean isCap(String w)
{
   return Character.isUpperCase(w.charAt(0));
}
thanks your idea helped greatly i did that and saw that i needed to change while with if but encountered a problem that the program wouldn't consider the last word as last character isn't the whitespace.so i did it using StringTokenizer.

I'M UPLOADING THE SNIP OF CHANGES AND OUTPUT IN CASE ANYONE WANTS TO HAVE A LOOK AT IT.
BUT MORE SUGGESTIONS ARE ALWAYS WELCOME
 

Attachments

  • cap2.PNG
    cap2.PNG
    27.2 KB · Views: 161
  • cap.PNG
    cap.PNG
    26.7 KB · Views: 169
  • cap.PNG
    cap.PNG
    26.7 KB · Views: 165
  • #13
pasmith said:
Splitting a string into substrings based on the occurence of a particular character is a common task for which there is a library function:
Java:
   String[] words = sent.split(' ');
This will probably solve your indexing error, because you will then only need to check the first character of each word.

You can replace isCap with
Java:
public boolean isCap(String w)
{
   return w.charAt(0) >= 'A' && w.charAt(0) <= 'Z';
}
or, even better because it correctly handles things like 'Å',
Java:
public boolean isCap(String w)
{
   return Character.isUpperCase(w.charAt(0));
}
thanks your idea helped greatly i did that and saw that i needed to change while with if but encountered a problem that the program wouldn't consider the last word as last character isn't the whitespace.so i did it using StringTokenizer.

I'M UPLOADING THE SNIP OF CHANGES AND OUTPUT IN CASE ANYONE WANTS TO HAVE A LOOK AT IT.
BUT MORE SUGGESTIONS ARE ALWAYS WELCOME
jedishrfu said:
My post was a hint as the index function returns a -1 when there are no spaces and so youve set your i variable to -1 with the possible and likely subsequent fail you observe.

You should test for it and decide what to do.
thanks for your help.I came up with StringTokenizer and it's working fine now.
 
  • Like
Likes jedishrfu

FAQ: Problem with this Java string program

1. What is a Java string program?

A Java string program is a computer program written in the Java programming language that manipulates and processes strings, which are sequences of characters. Java provides built-in methods and functions for working with strings, making it a popular choice for string processing tasks.

2. What are some common problems encountered when working with Java string programs?

Some common problems with Java string programs include incorrect syntax, incorrect use of string methods, and issues with handling special characters. It is important to carefully read and understand the documentation for string methods and to test the program thoroughly to catch any errors.

3. How can I troubleshoot a problem with a Java string program?

To troubleshoot a problem with a Java string program, you can use debugging tools such as breakpoints, print statements, or a debugger. These tools can help you identify where the problem is occurring in your code and what values are being passed to different variables and methods.

4. What are some best practices for writing a Java string program?

Some best practices for writing a Java string program include using meaningful variable names, commenting your code, and using string methods efficiently. It is also important to handle potential errors and exceptions gracefully to prevent unexpected program crashes.

5. Are there any resources available for learning more about Java string programs?

Yes, there are many resources available for learning more about Java string programs. These include online tutorials, documentation from Oracle (the creators of Java), and books on Java programming. You can also join online communities or forums where you can ask questions and learn from others' experiences.

Similar threads

Replies
7
Views
2K
Replies
2
Views
1K
Replies
7
Views
2K
Replies
5
Views
2K
Replies
2
Views
1K
Replies
1
Views
1K
Replies
2
Views
1K
Replies
4
Views
8K
Back
Top