• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Out of bounds exception

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Any ideas why I'm getting this error? Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 64 at java.lang.String.charAt(String.java:658) at ReverseString.main(ReverseString.java:8)



 
Josh Diamond
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
worked it out. It's because charAt is 0 index based so  you have to do charAt(i-1).
 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Or alternatively you could modify the parts of the for-statement to adjust for the -1 you need to do throughout.
 
Marshal
Posts: 79180
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don't make a new variable length.
Remind yourself of the normal format of a for loop to traverse an array:-
for (int i = 0; i < myArray.length; i++) ...
and to do the same backwards:-
for (int i = myArray.length - 1; i >= 0; i--) ...
I think you shou‍ld always use those formats as a starting point for for statements, even if you have to change them later. In the case of a String write text.length() rather than myArray.length.

You will probably get faster execution if you don't print the characters individually; append them to a StringBuilder object and print that.
reply
    Bookmark Topic Watch Topic
  • New Topic