Method from class does not work

I try to set up a short array and display four squares with random position and size. But I always get a syntax error. I spend lots of time comparing my code to other examples and they are all running, but mine is not. :face_with_monocle: Do you see what I did wrong here?

A[] squares = new A[4];

void setup() {
  size(600, 600);
  for(int i = 0; i < 4; i++) {
    squares[i] = new A(x, y, w, h);
  }
}

void draw() {
  background (250);
  for (A s : squares) {
    do();
    display();
  } 
}

class A {
  float x, y, w, h;
  
  void do() {
    x = random(20, 300);
    y = random(40, 500);
    w = random(100, 200);
    h = random(30, 110);
  }
  
  void display() {
    rect(x, y, w, h);
  }
}

Thanks for your help.

1 Like

Hello,

References:

Your code with modifications:

A[] squares = new A[4];

void setup() {
  size(600, 600);
  for (int i = 0; i < 4; i++) {
    squares[i] = new A();
  }
}

void draw() {
  background (250);
  for (A s : squares) {
    s.doit();
    s.display();
  }
}

class A {
  float x, y, w, h;

  void doit() {
    x = random(20, 300);
    y = random(40, 500);
    w = random(100, 200);
    h = random(30, 110);
  }

  void display() {
    rect(x, y, w, h);
  }
}

I only took a quick look at this to get you started… modify as required.

It did not seem to like do() (this may be reserved) so changed it to doit().

Consider adding a constructor to your class and make an array of rectangle data in setup().

It will take some time to get comfortable with OOP.

:)

1 Like

Yeah, you need s. before these

Because they are hidden inside the class, we need to name an object to call those functions (or methods).

When we just say do or display, it would refer to functions outside the class, functions like draw() or setup() that you don’t have.

Chrisir

1 Like