Reputation: 55
I'm trying to create an accessor for a custom object, Room
, which has a grid of tiles each with an integer value. I want the getSteps
method to return that integer value, given coordinates for the associated Room
object; I also want the steppedOn
method to increment it by one.
public Room(int tilesLong, int tilesWide) {
length = tilesLong + 2;
width = tilesWide + 2;
}
private int getSteps(int tileX, int tileY) {
int steps = this[tileX][tileY]; //Problem code
return steps;
}
public void steppedOn(int tileX, int tileY) {
System.out.println(room[tileX][tileY] + 1);
}
I understand this probably isn't the correct approach, but I'm lost on how else to do it.
Upvotes: 0
Views: 3227
Reputation: 484
online:
int steps = this[tileX][tileY]; //Problem code
you are trying to save you are calling an array
improperly
First, you will need to declare an array
. and in your signature, state the value you want to pass into the array. so it will look something like this:
public class room {
int length, width;
int[][] steps;
public room(int tilesLong, int tilesWide) {
length = tilesLong + 2;
width = tilesWide + 2;
steps = new int[width][length];
}
private int getSteps(int tileX, int tileY, int step) {
this.steps[tileX][tileY] = step;
return steps[tileX][tileY];
}
public void steppedOn(int tileX, int tileY) {
System.out.println(steps[tileX][tileY] + 1);
}
}
Upvotes: 0
Reputation: 12819
According to the docs for this
:
Within an instance method or a constructor,
this
is a reference to the current object — the object whose method or constructor is being called.
So in your getSteps()
method you are trying to call [tileX][tileY]
on an object which doesn't really make sense. If the object has a 2d array
class variable you need to call [tileX][tileY]
on the array
and not directly on this
.
I also want the
steppedOn
method to increment it by one.
In your steppedOn()
method you only print the number plus one. However this just increments the number that you print out, not the actual value. To actually increment the value do
public void steppedOn(int tileX, int tileY) {
System.out.println(room[tileX][tileY]++);
}
Upvotes: 1