Problem with this Java string program

  • Context: Comp Sci 
  • Thread starter Thread starter anyonebutangel
  • Start date Start date
  • Tags Tags
    Java Program String
Click For Summary

Discussion Overview

The discussion revolves around a Java programming problem where participants are trying to identify the frequency of words beginning with an uppercase letter in a given sentence. The focus is on debugging a specific implementation that results in a runtime error, specifically a "STRING INDEX OUT OF BOUNDS EXCEPTION." The conversation includes technical explanations, proposed solutions, and clarifications regarding the code structure.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning
  • Homework-related

Main Points Raised

  • One participant describes the problem with accessing a character beyond the end of a string, indicating a potential source of the runtime error.
  • Another participant suggests using the `split` method to divide the string into words, which may help avoid the indexing error by simplifying the checks for uppercase letters.
  • There is a proposal to modify the `isCap` method to improve its functionality, including a suggestion to use `Character.isUpperCase` for better handling of characters.
  • Concerns are raised about the handling of strings without spaces, questioning what the `indexOf` function returns in such cases.
  • Participants discuss the implications of the algorithm's structure, particularly the use of a while loop that could lead to infinite looping or incorrect indexing due to its dependence on the variable modified within the loop.
  • A suggestion is made to rename variables for clarity and to improve the overall understanding of the algorithm's purpose.

Areas of Agreement / Disagreement

Participants express differing views on how to handle the string parsing and the implications of the current implementation. While some propose specific changes to the code, others highlight potential issues without reaching a consensus on the best approach to resolve the runtime error.

Contextual Notes

There are limitations regarding the assumptions made about the input string, particularly concerning the presence of spaces. The discussion also reflects constraints related to adhering strictly to the original problem requirements, which may limit the applicability of suggested solutions.

Who May Find This Useful

This discussion may be useful for students or individuals working on Java programming assignments, particularly those focused on string manipulation and debugging runtime errors in their code.

anyonebutangel
Messages
40
Reaction score
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

Last edited by a moderator:
Physics news on Phys.org
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.
 
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
 
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:
Splitting a string into substrings based on the occurrence 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));
}
 
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 occurrence 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.
 
What if the string has no spaces? What does the index function return?
 
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.
 
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   Reactions: sbrothy
  • #12
pasmith said:
Splitting a string into substrings based on the occurrence 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: 230
  • cap.PNG
    cap.PNG
    26.7 KB · Views: 242
  • cap.PNG
    cap.PNG
    26.7 KB · Views: 251
  • #13
pasmith said:
Splitting a string into substrings based on the occurrence 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   Reactions: jedishrfu

Similar threads

  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 2 ·
Replies
2
Views
7K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 1 ·
Replies
1
Views
2K