• Post Reply Bookmark Topic Watch Topic
  • New Topic

String Index out of bounds problem  RSS feed

 
sam hello
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This program is to use the keyboard keys to play notes. i get a different string index out of range for each key i press, ranging from 49 for the 1 to 109 for the m.
but i always get this error message. i am new to java, and any help would be appreciated since i've checked a bunch of forums and haven't found the answer to quite this kind of problem.
This is my code. The exception is thrown at this line: nextnote = keyboard.charAt(key);
 
Keith Rainey
Ranch Hand
Posts: 66
Android Eclipse IDE IntelliJ IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Index out of bounds means you are trying to use an invalid index (one which it outside the legal range). Your keyboard String has 36 characters in it... if you try to access and index less than 0 or higher than 36, the code will fail.

Find out what value is being returned to 'key' and work from there.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Keith Rainey wrote:Your keyboard String has 36 characters in it... if you try to access and index less than 0 or higher than 36, the code will fail.

I think you meant higher than 35.

@sam: It's a very difficult thing to get used to at first, but Java arrays and Strings are always indexed from 0.
That means that for an array or String of 36 characters, charAt(0) gets you the first and charAt(35) gets you the last.

Winston
 
Keith Rainey
Ranch Hand
Posts: 66
Android Eclipse IDE IntelliJ IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote:
Keith Rainey wrote:Your keyboard String has 36 characters in it... if you try to access and index less than 0 or higher than 36, the code will fail.

I think you meant higher than 35.




Yes.. higher than 35. Thanks for catching that.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!