# Array causing NullPointerException error?

**URL:** <https://discourse.processing.org/t/array-causing-nullpointerexception-error/28614>\
**Category:** Beginners\
**Created:** [March 17, 2021, 4:32pm UTC](https://discourse.processing.org/t/array-causing-nullpointerexception-error/28614 "2021-03-17T16:32:15Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mattyjak](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/mattyjak/32/16777_2.png) [@Mattyjak](https://discourse.processing.org/u/Mattyjak)\
**Post date:** [March 17, 2021, 4:32pm UTC](https://discourse.processing.org/t/array-causing-nullpointerexception-error/28614/1 "2021-03-17T16:32:15Z")

</div>

Hello everyone! Today, I’ve decided to start working on my game. I had some old code for player movement that I wanted to see if I could port over, and here it is. Unfortunately, it keeps throwing me a ‘NullPointerException’ error and crashing the sketch. If anyone could help me, please do!

```auto
int[] keys; //I TRIED BOOLEAN AS I THOUGHT IT WOULD WORK BETTER BUT NO DICE.
void keyPressed() {
  keys[keyCode] = 1; //IT ERRORS HERE
  //print(keyCode);
 // print(key);
}
void keyReleased() {
  keys[keyCode] = 0; //AND HERE
//AND BASICALLY ANYWHERE I CALL keys[]. 
}

void PlayerMovement() {
  if (keys[65] == 1 || keys[37] == 1) {
    accl.x-=ship_acc_amount;
  } else if (keys[68] == 1 || keys[39] == 1) {
    accl.x+=ship_acc_amount;
  }
  if (keys[87] == 1|| keys[38] == 1) {
    accl.y-=ship_acc_amount;
    //pship.y += tempy;
  } else if (keys[83] == 1 || keys[40] == 1) {
    accl.y+=ship_acc_amount;
  }
  //ON KEY PRESS, INCREASE THE PLAYER'S ACCELERATION BY THE ACCELERATION AMOUNT. 

  pship.x+=accl.x;
  pship.y+=accl.y; 
  //ADD THE ACCELERATION FORCE TO THE PLAYER

  //ENSURE SPEED CAP:
  if (keys[83] == 1 || keys[40] == 1 || keys[87] == 1 || keys[38] == 1 || keys[68] == 1 || keys[39] == 1 || keys[65] == 1 || keys[37] == 1) {
    //unimportant speed cap code
 }
};

```

Normally I would set the value of the keycode in the array to true, but it didn’t work so I tried an integer value instead. I think it could be that the value assigned is undefined? But I’m not too sure.

---

<div class="post-metadata">

**Author:** ![Mattyjak](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/mattyjak/32/16777_2.png) [@Mattyjak](https://discourse.processing.org/u/Mattyjak)\
**Post date:** [March 17, 2021, 4:45pm UTC](https://discourse.processing.org/t/array-causing-nullpointerexception-error/28614/2 "2021-03-17T16:45:41Z")

</div>

NEVERMIND! I wasn’t actually creating the array using the constructor method.  
Here’s the new code, (and also the solution to my problem):

```auto
Boolean[] keys = new Boolean[150];
void keyPressed() {
  keys[keyCode] = true;
  //print(keyCode);
 // print(key);
}
void keyReleased() {
  keys[keyCode] = false;
}

```
