I’m currently trying to draw shapes with 2D Arrays. In my class there is a global array defined with public char canvas[][];
Up until now, I have only declared arrays with char canvas[][] = new char[height][width];
If this Array has already been declared, and I’m not supposed to amend the code I’ve been given, how do I call an instance of that array so that I can use it?
thanks.
(edit)
class DrawingSystem {
public char canvas[][];
public static void makeNewCanvas(int tmpWidth, int tmpHeight) {
canvas[][] = new char[tmpHeight][tmpWidth];
for (int row=0; row<tmpHeight; row++) {
for (int col=0; col<tmpWidth; col++) {
canvas[row][col] = ' ';
}
}
}
You have an incompatibility between static methods and instance variables.
Think about it this way: an instance variable is associated with a specific instance of a class; a static variable is associated with the class itself. You call static methods via the class:
Whereas you call an instance method via an instance of the class:
In the code you posted, there’s an instance variable (“canvas”) being set in a static method (
mainis associated with the Class, not an instance).Therefore, you’ll need to create instance methods to modify/update your “canvas”, and create an instance of the class within the static function. This object (an “instance”) can be used to update the instance variable.
Here’s an example:
This obviously isn’t a one-to-one correlation to your assignment, but I’m sure you’ll be able to adapt it to what you’re doing 🙂