There is another thread with the exact same project as mine but it is older and inactive. I suggest reading it as it explains the entire project: http://forums.d2jsp.org/topic.php?t=42738700&f=124
Basically I creating a Battleship program in java. We are required to create 3 classes: Ship, Square, and BattleBoard. Ship and square share information with each other to BattleBoard.
I have finished Ship and Square, tested both, and I have pretty much finished the requirements for BattleBoard. However, to test the code, we are using a toString method. I have a test in BattleBoard where I add a ship that is length:1 start row: 1 start col:1 and I should get "1 - - - -" however I get "1 1 1 1 1".
My toString code in BattleBoard:
Code
for (int i = 0; i < squares.length; i++) {
for (int j = 0; j < squares[i].length; j++) {
squares[I][j] = new Square();
if (!square.hasShip() && !square.hasBeenHit()) {
toString += "- ";
} else if (square.hasBeenHit() && !square.hasShip()) {
toString += "W ";
} else if (square.hasBeenHit() && square.hasShip()) {
toString += "R ";
} else if (!square.hasBeenHit() && square.hasShip()) {
//Returns length of ship if there is a ship that hasn't been hit
if (ship.getLength() == 1) {
toString += "1 ";
} else if (ship.getLength() == 2) {
toString += "2 ";
} else if (ship.getLength() == 3) {
toString += "3 ";
} else if (ship.getLength() == 4) {
toString += "4 ";
}
}
}
toString += "\n";
}
return toString;
and my addShip code in BattleBoard:
Code
ship = new Ship(length, isHorizontal, startRow, startCol);
if (square.hasShip() == true || startRow < 0 || startCol < 0 || startRow > numberOfRows || startCol > numberOfColumns) {
return false;
} else {
if (isHorizontal == true) {
//ship = new Ship(length, isHorizontal, startRow, startCol);
for (int i = 0; i < ship.getLength(); i++) {
if (startCol > numberOfColumns) {
return false;
} else {
squares[startRow][i] = new Square();
square.addShip(ship);
startCol++;
}
}
} else if (isHorizontal == false) {
//ship = new Ship(length, isHorizontal, startRow, startCol);
for (int i = 0; i < ship.getLength(); i++) {
if (startRow > numberOfRows) {
return false;
}
//squares[i][startCol] = new Square();
square.addShip(ship);
startRow++;
}
}
ships[shipIndex] = ship;
shipIndex++;
return true;
}
}
Any help would be appreciated
Thanks