• Post Reply Bookmark Topic Watch Topic
  • New Topic

String index out of bounds?  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, so I'm just trying to write a basic little program that reverses the letters in someone's name. I thought I had it down, but I guess not. Here's the code, and the error I'm getting is:

java.lang.StringIndexOutOfBoundsException:
String index out of range: 11 (in java.lang.String)

(11 is the length of the name I'm inputting)


 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I added code tags to your post; always use them, because you can see how much better it looks

String indices and List indices and array indices all start at 0, so an 11‑letter String goes from 0 to 10. You can't use index 11.
 
Justice Smith
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! I changed my charAt(l) to charAt(l-1), and my loop parameter to l >= 1 instead of l >= 0. Would there have been a simpler way to do it? Also, how do I add the code tags?
 
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Justice Smith wrote:Thanks! I changed my charAt(l) to charAt(l-1), and my loop parameter to l >= 1 instead of l >= 0. Would there have been a simpler way to do it?

Yes. Just start your loop with int l = name.length()-1 instead of int l = name.length().

Justice Smith wrote:Also, how do I add the code tags?

There is a "code" button visible when you type your post.
 
Justice Smith
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! That should do it for me.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!