I\'m working on a Battleship project in my class and I\'ve gotten mostly everyth
ID: 3824924 • Letter: I
Question
I'm working on a Battleship project in my class and I've gotten mostly everything taken care of and the code compiles without issue. However, when running it, these particular lines (indicated by the bold arrows) produce a NullPointerException. I cannot for the life of me figure out what's causing it. Any help would be appreciated
if (isHorizontal) {
if (startCol + length > numberOfColumns + 1) {
placeable = false;
}
else {
for (int i = startCol; i < startCol + length; i++) {
if (squares[startRow][i].hasShip()) { <--------
placeable = false;
break;
}
}
}
}
else {
if (startRow + length > numberOfRows + 1) {
placeable = false;
}
else {
for (int j = startRow; j < startRow + length; j++) {
if (squares[j][startCol].hasShip()) { <---------
placeable = false;
break;
}
}
}
}
Explanation / Answer
Hi friend, NullPointerException exception means, you are calling hasShip() methos on null object
It means: squares[startRow][i] is null and squares[j][startCol] is null
Since you have not posted whole code so i do not about squares[][] array.
So, please check you have created object for entry : squares[startRow][i] and squares[j][startCol]