//Checks a column
for (i = 0; i < 9; i++) {
if (this.board[i][col].getNumber() == number) {
return false;
}
}
//Checks a 3x3 box
iStart = row - row % 3;
jStart = col - col % 3;
for (i = iStart; i < iStart + 3; i++) {
for (j = jStart; j < jStart + 3; j++) {
if (this.board[i][j].getNumber() == number) {
return false;
}
}
}
this.board[row][col].setNumber(number);
return true;
};
You will recognize pieces of code f rom your homework on pa ge 187. I had to modify
the part that checks the rows beca use we now don’t have primitive values but rather
object references stored in r ows. That means we cannot use the indexOf() a rray
method to search for a value. You’ll also notice tha t I left out the auxiliary variable
exists beca use it is not n ecessary. The method can simply return false if and as
soon as it discovers th at a number cannot be placed. If, however, the number can be
placed, then all the for loops terminate normally, the number is stored into the cell,
and the method returns tru e. It is importa nt that we return true upon successfully
entering a numb er because the code that calls this method sometimes n eeds to know
whether or not the operation was successful.
Mike: The setNumber() method called from the second to the last line belongs to
the Cell class, doesn’t it?
Professor: I ndeed it does.
Maria: What’s the use of the setNumber(null) call placed at the beginning of the
method?
Professor: It can easily happen that the play er enters the same number into th e same
cell twice after chang ing his/her mind several times. Notice that our method checks
all the nine cells of a certain section, including the one whose value we’re just setting.
Thus, we first have to remove the old number by setting the cell to null or else the
entered number is also compared to the one it is going to replace anyhow. Had we not
done this, entering the same num ber into the same cell twice would be recognized as
an invalid action. A part from that, this line delete s the old number from the cell even
if the new number cannot be placed.
224 Meeting 11. Building Your Own Objects
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.33.243