File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Index Exception question

 
M Wallace
Greenhorn
Posts: 3
Eclipse IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am trying to understand the error message I am getting with this code. I wrote this program for the sole purpose of changing the index value from the tutorial in the book I am working through. In the line assigning a value to 'c2', when I leave the index value at 0 it works fine and grabs the next value from the string 'test' I am entering. If I change the value to a 1 or 2, it throws the below error message. Can anyone let me know why my code is throwing this error as from my understanding thus far, 1 is within range of the string I am using? I have checked some java documentation but the most I've gotten from it is the error is caused by me trying to access a value outside the index range. Maybe I'm using either charAt() or findWithinHorizon() wrong?

Error message:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(Unknown Source)
at ReadingCharsTest.main(ReadingCharsTest.java:17)

Code:

Thank you in advance!

 
Paul Clapham
Sheriff
Pie
Posts: 20171
25
MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"charAt(0)" will throw that exception if the String you call it on has zero characters. Likewise "charAt(1)" will throw that exception if the String you call it on has one character (or zero).

So it looks like your expectation of what the "findWithinHorizon" method is returning was incorrect. I suggest debugging to find out what it actually returns, versus what you expected it to return.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic