File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes String Index Exception question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Index Exception question" Watch "String Index Exception question" New topic
Author

String Index Exception question

M Wallace
Greenhorn

Joined: Jul 28, 2012
Posts: 3

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!


The two people in this world are those that do, and those that don't.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

"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.
 
subject: String Index Exception question