Java Reference
In-Depth Information
r e s u l t+= ( l i n e ++)+ "|" ;
for (Cell cell : row) {
result += cell+ "" ;
}
return result ;
}
The code iterates over all rows of the grid. For each row, it adds to result a new line
and the line number. Note that the expression: result += (line++)+" | "; means add
the current value of the variable line to the variable result and then increment the value
of the variable line by 1. The line can be rewritten as follows.
result = result + (String)( line) + "|" ;
line = line+1;
Remember that adding an integer and a string concatenated the integer to the string.
This is why we did not need the explicit cast to String in the original expression.
Next, the code iterates over all cells of the row. The statement: result += cell+" "
is equivalent to result = result+ cell.toString()+" " . In other words, the toString
method for the cell object is automatically called to convert the object into a string.
The complete code for the Board class is presented next.
import java . util . ;
public class Board {
public static final int BOARD SIZE = 10;
public static final boolean HORIZONTAL = true ;
public static final boolean VERTICAL = false ;
public static final
int [ ] placement = { 5,4,3,2,2,1,1 } ;
private Cell [ ] [ ] grid = new Cell [BOARDSIZE ] [ BOARD SIZE ] ;
private Ship [] ships = new Ship [ placement . length ] ;
public String toString() {
String result= " 0123456789\n ----------" ;
int line = 0;
for (Cell[] row: grid)
{
result+= "\n" ;
result+= (line++)+ "|" ;
for (Cell cell: row)
{
result += cell+ "" ;
}
return result ;
}
public Cell getElement( int row ,
int column)
{
if ((row > =0&&row < BOARD SIZE) &&
(column > =0&&column < BOARD SIZE) )
{
return grid [row][ column];
return null ;
}
 
Search WWH ::




Custom Search