NullPointerException by creating an object

Hello !
I wrote a program in which I created a class called Ro with objects : circles who goes on a random X position
But by running the program it craches. It writes " NullPointerException" and
“c[i++] = new Ro(width1/10,30+i60);” is highlighted.

The program ran once, I modified it and it don’t worked again so I deleted my modification with ctrl Z but it doesn’t worked.

Can you help me ?

  String nb_pop = "10";
  int tempo = 0;
  boolean start = false;
  boolean select = false;
  boolean newstart = false;
  int index;
  
  Ro[ ] c; 
  
  void setup(){
   size(1000,600);
  
  }
  
  class Ro{
    float x;
    float y;
    
    Ro(float x, float y){
      this.y = y;
      this.x = x;
    }
    void show(){
      fill(0);
      ellipse(x,y,30,30);
      println(x);
      println(y);
    }
    void run(){
      x += random(1,width*8/10);
    }
  }
  
  
  void draw(){
    background(255);
    rectMode(CENTER);
    textAlign(CENTER,CENTER);  strokeWeight(4);
    fill(111,222,111,111);
    rect(width/2,height*3/4,width/6,height/10,width/32);
    textSize(30);
    fill(0);
    text("Start",width/2,height*3/4);
    text(nb_pop,width/2,height*2/5);
  
      tempo +=1; 
      if(mousePressed){
        if(mouseY > height/2){
          start = true;
        }
      }
      if(start == true){
        background(255);
        line(width*3/4,0,width*3/4,height);
        for(int i=0; i < 10; i++){
          fill(255);
          c[i++] = new Ro(width*1/10,30+i*60);
          c[i++].run();
          c[i++].show();
        noLoop();
        }
        
      }
  }

Thanks

Hi @Exartyss,

Your array c has currently a size of 0 elements.

And you try to put more elements than capacity to it…

Short … You need to tell how much elements it should have …

Ie…

c = new Ro[10];

Cheers
— mnse

PS: also this will fail if you handle the index that way, as I increases on each step …

          // will crash
          c[i++] = new Ro(width*1/10,30+i*60);
          c[i++].run();
          c[i++].show();
         // should be
          c[i] = new Ro(width*1/10,30+i*60);
          c[i].run();
          c[i].show();
  • Actually Ro[] c; merely creates a variable of type Ro[].
  • But the array doesn’t exist yet!
  • If you know how many Ro[] objects you’re gonna need, it’s better to create the array at the same time you’re declaring its variable: Ro[] c = new Ro[10];
2 Likes

Hi @GoToLoop,

Sure! But thought it makes clearer what’s the issue in that case … :wink:

Cheers
— mnse

2 Likes

Oky
It works. Thanks a lot!
you too @GoToLoop

1 Like