Fix NullPointerException error

I have an error in my code and I’m not sure how to fix it.I’m relatively new to Arrays.
I want to sort the numbers given in Arreglo into two other arrays, one for positive numbers and the other for negative.

Error is on line 25

int N=4;
float [] pos;
float [] neg;

void setup(){
  float [] Arreglo = {-1, 5, -3, 2};
  println("Valores del Arreglo");
  println(Arreglo);
  
  posNeg(Arreglo);
  println("Numeros positivos y cero:");
  println(pos);
  println("Numeros negativos:");
  println(neg);
}


void posNeg (float [] Arreglo){
  for (int i=0; i<=N; i++){
    float comp = Arreglo[i]; 
    if (comp>=0){
      pos[i]=comp;
    }
    else{
      neg[i]=comp;
    }
  }
}

you need to initialize the arrays pos and neg with empty slots (before setup)

and for loop must be with < N instead of <= N

Here is a running example BUT as you can see, pos and neg contain empty slots (0.0 between the correct values) - can you think of a way to improve this? maybe look at append in the array section of the reference.

Hey, and welcome to the forum, great to have you here!

Warm regards,

Chrisir

int N=4;
float [] pos=new float [4]; // new
float [] neg=new float [4];

void setup() {
  size(111, 111); 
  float [] Arreglo = {-1, 5, -3, 2};
  println("Valores del Arreglo");
  println(Arreglo);

  posNeg(Arreglo);
  println("Numeros positivos y cero:");
  println(pos);
  println("Numeros negativos:");
  println(neg);
}


void posNeg (float [] Arreglo) {
  //
  for (int i=0; i<N; i++) {  // here 
    float comp = Arreglo[i]; 
    if (comp>=0) {
      pos[i]=comp;
    } else {
      neg[i]=comp;
    }
  }
}

1 Like

Thanks!
I did think of initializing the Array but found the same problem as you as the lenghtof the array isn’t defined until the last part and there could be no negative numbers for example.
Thanks for the inputon why I was getting the error and the welcoming:)

Yeah, start with empty arrays and use command append