2

I have created the following sketch in Processing (Java):

ArrayList<Piece> pieces = new ArrayList<Piece>();

void setup() {
  size(300, 300);
  pieces.add(new Piece(100, 200)); // I ADD ONE PIECE TO THE ARRAY LIST 
}

void draw() {
  background(0);
  for (int i = 0; i < pieces.size(); i++) {
    Piece p = pieces.get(i);
    p.display(); // I WANT TO DRAW THE PIECE I'VE CREATED IN SETUP()
  }
}

class Piece {
  int x;
  int y;

  Piece (int x, int y) {
    x = x;
    y = y;
  }

  void display() {
    fill(255);
    ellipse(x, y, 30, 30); // AS X IS 100 AND Y IS 200, A BALL SHOULD BE DRAWN AT THOSE COORDINATES, BUT INSTEAD THE BALL IS DRAWN AT 0,0. WHY THAT?
  }
}

I add one piece to the array list which has coordinates (100,200). When I execute p.display() it draws the ellipse at 0,0 and not at 100,200. Why does this happen?

1
  • Where is ellipse defined? Commented Feb 17, 2015 at 20:41

1 Answer 1

6

I believe

x = x;
y = y;

should be

this.x = x;
this.y = y;

in your Piece() constructor. x=x just sets the value to itself, using the this keyword will set your Piece's values according to the ones you are trying to pass in.

Sign up to request clarification or add additional context in comments.

1 Comment

@DavidDejori You should accept the answer if that solves your question. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.