I'm coding a wordsearch puzzle and I need to write a helper method called isHorizontalSpaceFree()
.
The method should check whether (starting from aRow and aCol) there is enough free space to insert word into letterGrid(left to right)
. If there is enough space, the method should return true, otherwise it should return false.
I need the method to return an out of bounds exception if the word length exceeds the end of the array as well.
Here is my code so far
public boolean isHorizontalSpaceFree(int aRow, int aCol, String word)
{
boolean result = true;
if (aCol < NUMBER_COLS - word.length())
{
int i = aCol;
while (aCol < NUMBER_COLS - word.length())
{
if (letterGrid[aRow][aCol] != BLANK_ELEMENT
|| aCol > NUMBER_COLS - word.length())
{
result = false;
}
aCol++;
}
}
else
{
result = false;
}
return result;
}
I hope it's not too far away.
Based on your code, I'm assuming you want the method to return true if:
aCol
andNUMBER_COL
to fit the wordaRow
betweenaCol
andaCol + word.length()
areBLANK_ELEMENT
sGiven the above, the following should work:
Edit: As mentioned in Andreas_D answer, this method shouldn't really be throwing an exception, rather returning just
true
andfalse
.