Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Question over an error message in exercise 3.19

+7 votes
Spoilers for the problem in case you wanted to work on it without prior knowledge.

Here is the code i have so far:

public class YourClassNameHere {
    public static void main(String[] args){
        printReverse("hello there");
    public static void printReverse(String stuff){
        int k=stuff.length();
          for (int i=k; i>0; i--){

When i run it, i get the error message:

"java.lang.StringIndexOutOfBoundsException: String index out of range: 11"

But i don't understand how it's out of bounds. Its nearly the same code as the previous problem, so i don't know why i'm getting this "out of bounds" issue when in the last one it worked fine.
asked Sep 22, 2016 in CSC 211 (F16) by Brent Pierce (100 points)
Brent -- please do not post source code to the PracticeIt *Exercises* on the Q&A site.  (Posting source code for the Self-Checks is fine.)  You may ask questions about the Exercises, for example:
I'm working on Exercise 3.19, and I got this error "java.lang.StringIndexOutOfBoundsException: String index out of range: 11".  Any ideas what would cause this?

1 Answer

+2 votes
stuff.length() returns 11, right? But since the index starts at 0, the last char is at 10.

Use (int i = k-1; i >= 0; i--)

Oh, and, I think you want System.out.print [not println].
answered Sep 22, 2016 by Jon Clauss (100 points)
Thank you very much! I was thinking it was some sort of scope issue with the error I was getting, but the -1 did the trick!
Possibly a bit too direct of help in solving this Exercise (as opposed to self-checks, where any amount of help is fine).  I think that simply

"stuff.length() returns 11, right? But since the index starts at 0, the last char is at 10."

should be a sufficient hint here...