Java – If-else alternative


I have a program I am writing that works on the principle of populating a two dimensional array to check the winning condition, it's noughts and crosses so the two dimensional array is populated on the click of a button, 1 for a circle, 2 for a cross, then the checkWin() will work on this principle, not the actual code…

if (myArray[0][0] == 1 && myArray[0][1] == 1 && myArray[0][2] == 1){
    setBoolWinVal = true;
} else {
    if(myArray[0][0] == 2 && myArray[0][1] == 2 && myArray[0][2] == 2){
    setBoolWinVal = true;

you can see immediately that for every winning condition this will be messy, is there any way of rewriting this check for win to shorten it a little?

Best Solution

This looks like homework, so I won't give it away completely. But notice a few things:

  • You win when you have three of the same thing in a row, in a column, or along a diagonal.

  • It's not that you need to check whether there are three noughts or three crosses in a line, but rather that there are three of the same thing in a line.

You could start by writing a function which determines whether a row, column, or diagonal has three of the same kind of thing (and that thing isn't a blank cell). Then call that function once for each row, column, and diagonal.