JAVA - can somebody help me write this test code?! private static void testCheck
ID: 3918061 • Letter: J
Question
JAVA - can somebody help me write this test code?!
private static void testCheckLost() {
//FIXME
}
following is my code that I have written for actual program
/**
* Checks the cells of the game board to determine if all the ships have been sunk.
*
* @param board The game board to check.
* @return true if all the ships have been sunk, false otherwise.
*/
public static boolean checkLost(char board[][]) {
boolean checkPoint = true;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] != Config.WATER_CHAR && board[i][j] != Config.HIT_CHAR
&& board[i][j] != Config.MISS_CHAR) {
checkPoint = false;
}
}
}
return checkPoint;
}
Explanation / Answer
public static boolean checkLost(char board[][])
{
// traverse the row
for (int i = 0; i < board.length; i++) {
// traverse the columns
for (int j = 0; j < board[i].length; j++) {
// if current ship is not sunk
if (board[i][j] != Config.WATER_CHAR && board[i][j] != Config.HIT_CHAR && board[i][j] != Config.MISS_CHAR)
{
// if even one ship is not sunk, then return false immediately
// if we don't return immediately, then the function will always return
// only if the last ship has sunk or not
return false;
}
}
}
// when all the ships have sunk
return true;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.