Hello Guest

[FIXED] ArrayIndexOutOfBoundsException in Keyboard

  • 3 Replies
  • 7447 Views
[FIXED] ArrayIndexOutOfBoundsException in Keyboard
« on: September 10, 2012, 02:32:14 »
Hi, I tried mapping Key names to their values by looping through all the possibilities of the key indexes (I need that to easily make my key binding option panel).

So without further ado, here's the code proving the issue:

Code: [Select]
public static void main(String[] args) throws Exception {
Display.create();
Keyboard.create();


for (int i = 0; i < Keyboard.KEYBOARD_SIZE; i++) {
System.out.printf("% 3d: %s%n", i, Keyboard.getKeyName(i));
}


Keyboard.destroy();
Display.destroy();
}

When the variable i becomes 255 (KEYBOARD_SIZE - 1), I get an ArrayIndexOutOfBoundException.

The problem comes from the instantiation of the keyNames array which has a size of KEYBOARD_SIZE - 1, making the last available element be at index 254, and of course when I try to access 255, it fails.

I think my for loop is quite fair and shouldn't need adaptation (in case keyboards grow and use all the KEYBOARD_SIZE available), making the issue in LWJGL rather than in my code.

Meanwhile, I hardcoded 255 rather than Keyboard.KEYBOARD_SIZE in my loop.

Potential solution: Change line 219 of Keyboard.java: (against trunk revision 3797)

Code: [Select]
private static final String[] keyName = new String[255];to
Code: [Select]
private static final String[] keyName = new String[KEYBOARD_SIZE];

*

Offline ra4king

  • **
  • 58
  • I'm the King!
    • Roi's Website
Re: [BUG] ArrayIndexOutOfBoundsException in Keyboard
« Reply #1 on: September 10, 2012, 02:59:25 »
Oof, embarrassing off-by-one error :P

Nice find!
-Roi

*

Online spasi

  • *****
  • 2261
    • WebHotelier
Re: [BUG] ArrayIndexOutOfBoundsException in Keyboard
« Reply #2 on: September 10, 2012, 07:56:06 »
Thanks, fixed.

Re: [FIXED] ArrayIndexOutOfBoundsException in Keyboard
« Reply #3 on: September 12, 2012, 23:53:54 »
Thanks for being so quick! :)