Reputation: 1
Printing out a 2d character array is not difficult, but the way I need to do it seems to be.
My current goal is initialize a 2d character array, such that every cell contains '-'. This must be done within the constructor method. Below is what I have thus far.
public class GameOfLife {
public final int MAX_SIZE = 12;
// instance variables
private char [][] current = new char[MAX_SIZE][MAX_SIZE];
private char [][] next = new char[MAX_SIZE][MAX_SIZE];
Scanner keyboard = new Scanner(System.in);
/**
* Constructor for objects of class GameOfLife.
* Initializes the current array to '-'.
*/
public void GameOfLife() {
for ( int i = 0; i < MAX_SIZE; i++){
for ( int j = 0; j < MAX_SIZE; j++){
current [i][j] = '-';
}
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
for ( int i = 0; i < MAX_SIZE; i++){
for ( int j = 0; j < MAX_SIZE; j++){
sb.append(current[i][j]);
sb.append(" ");
}
sb.append("\n"); // add new line
}
return sb.toString(); // convert to String and return
}
}`
I know how to properly print it if it were just to be printed within this method; however, I must use the "GameOfLife" constructor in the following way. This next code is in the driver class, which is called "gameoflifedriver".
// Create a GameOfLife object
GameOfLife lifeGame = new GameOfLife();
System.out.print(lifeGame);
The problem that I am having is that the lifeGame will not print, and an odd error message occurs - GameOfLife@5d3892b3. I know there are ways to print it, but I cannot change any of the code in the driver class - so all of the edits must be in the GameOfLife code. Any thoughts?
Upvotes: 0
Views: 92
Reputation: 34146
You can override the toString()
method. Also you could use a StringBuilder
:
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for ( int i = 0; i < MAX_SIZE; i++){
for ( int j = 0; j < MAX_SIZE; j++){
sb.append(current[i][j]);
sb.append(" ");
}
sb.append("\n"); // add new line
}
return sb.toString(); // convert to String and return
}
Then you can print this representation with:
GameOfLife lifeGame = new GameOfLife();
System.out.print(lifeGame);
Note: Constructors don't have a return type, so you shouldn't declare it with return type void
:
public GameOfLife() {/* Constructor body */}
Upvotes: 2
Reputation: 119
The Class GameOfLife constructor should not have void return type (java rule). And the toString() method is good to implement.
Upvotes: 0