For a project I'm working on, I must implement a text based map which a player can navigate, interacting with certain objects on the map. Each time the player (user) picks up or puts down an object, the player's inventory is (supposed to be) displayed, for which I have written the following code:
ArrayList<GamePiece> inventory = new ArrayList<GamePiece>();
public String toString() {
String result = "";
for(int i = 0; i < inventory.size(); i++){
result += " " + inventory.get(i);
}
return result;
}
I am overriding the toString method so I can print out the elements in the ArrayList, but each time I do it simply prints the memory location. For instance, if I have a Pebble and a Stone in my inventory, and I call this method, it returns the following:
[Pebble@75b84c92, Stone@6bc7c054]
I think I'm doing something wrong in the toString method, I just can't figure it out. If you have any ideas I'd love to hear them, you were a great help with my last question so I have confidence!
Here is my Pebble class:
public class Pebble extends Rock {
private int pebbleWeight= 1;
public Pebble() {
}
public char charRepresentation() {
return 'P';
}
public String look() {
return "This object is very small, with rounded edges and speckled with dark colors.";
}
public String touch() {
return "Edges, shaped by millions of years of running water, are smooth.";
}
public int getWeight() {
return pebbleWeight;
}
public String getName() {
return "Pebble";
}
}
Here is the Stone class:
public class Stone extends Rock {
private int stoneWeight = 4;
public Stone() {
}
private int weight= 1;
public char charRepresentation() {
return 'S';
}
public String look() {
return "This object is about the size of your fist, with rounded edges and dark colors.";
}
public String touch() {
return "Edges, shaped by millions of years of running water, are smooth. Not too heavy...";
}
public int getWeight() {
return stoneWeight;
}
public String getName() {
return "Stone";
}
}
Rock class:
public class Rock extends GamePiece {
public Rock() {
}
public String listen() {
return "This object has no sound...";
}
}
GamePiece class:
public class GamePiece {
private int weight = 0;
private int x = 0;
private int y = 0;
public GamePiece() {
}
public int getWeight() {
return weight;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public char charRepresentation() {
return '?';
}
public String look() {
return "no description known";
}
public String listen() {
return "no voice yet";
}
public String touch() {
return "no texture yet";
}
public String getName() {
// TODO Auto-generated method stub
return null;
}
}