user5454232
user5454232

Reputation:

Calling toString on objects

I have a class Game that has a toString method.

I would like to iterate through an array using a nested for loop and then for each Tile element in the specified index of this array, print out a specific string based on that Tile's attributes which is inside the toString method that I have written in the Tile class.

If this is the appropriate logic for this, how can I implement this? I am unable to properly match parameters between the two toString methods.

public String toString(tileArr){
    for(int i = 0; i < rows; i++){      
        for(int j = 0; j < columns; j++){ 
            tileArr[i][j].toString(t);
        }   
        System.out.print("\n");
    }
    return "";
}

Upvotes: 0

Views: 396

Answers (1)

Andy Thomas
Andy Thomas

Reputation: 86381

You're mixing up two concepts: creation of a string in memory, and printing.

Your toString() method should not call System.out.println(). Instead, it should just be creating a string, which can be printed by some caller.

In addition, if you're trying to provide the conventional toString() method, it doesn't take any arguments. Since it's an instance method, it has access to the object's fields.

public class Game {
  private int rows, columns;
  private int tileArr[][];

  ...

  public String toString(){
      StringBuilder builder = new StringBuilder();
      for(int i = 0; i < rows; i++){      
         for(int j = 0; j < columns; j++){ 
            builder.append( tileArr[i][j].toString() );
            builder.append(" "); // If tiles need to be separated.
         }   
         builder.append("\n");
      }
      return builder.toString();
   }
}

Upvotes: 3

Related Questions