Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Searching Code: Out of Bound Index Error

 
Olivier Legat
Ranch Hand
Posts: 176
Chrome Mac Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone

I was working on a search method and I've almost completed it. However there's just one slight problem with it that can't seem to be able to fix. If I search for 1 character it works fine, but when I have two or more character the complier gives me an out of bound index error.

Here's the code:


And the error message:

java.lang.StringIndexOutOfBoundsException: String index out of range: 29
at java.lang.String.charAt(String.java:460)
at MainClass.main(MainClass.java:25)
Exception in thread "main"


java:25 (line 25) is where there's c[j] = str1.charAt(i+j). I messed around a bit if the for loops that have the variable i and j but it seems to have no effect.

Any suggestions?
:roll:
[ March 01, 2008: Message edited by: Olivier Legat ]
 
Ravikanth kolli
Ranch Hand
Posts: 179
Chrome Eclipse IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is it that you are actually trying to do in the inner forloop?

// j: Deviation to the right from i
for(int j=0; j<num; j++)
{
c[j] = str1.charAt(i+j);
}


Size of the string str1 is smaller than the index of (i+j). That is the reason for the arrayindexoutofboundsException.

try to access within the size bounds of the string str1.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic