Since you are using a multidimensional array, try using a nested for loop.
public boolean diagonal(char[ ][ ] theBoard, char thePlayer) {
boolean result = false;
int x, y; // These will tell you the coordinates of thePlayer if found on theBoard
for(int i = 0; I < theBoard.length; i++)
for(int j = 0; j < theBoard[i].length; j++)
if (thePlayer == theBoard[i][j]) {
result = true;
// Add if you want to know coordinates of the player
x = i;
y = j;
}
return result;
}
With a multidimensional array you need to know the values in both the row and column. Suppose you start at i = 0
, if you put in one loop and look for theBoard[i] [i]
, you will be looking at row 0 col 0, then you add 1 to i, i++
, now you are looking at row 1 col 1. You're skipping everything else. That's why you need a nested for loop to iterate over both the row and the column.
Look at the example below...
0 1 2 3 4 5
0 X X X X X X
1 X X X X X X
2 X X X X X X
3 X X X X X X
4 X X X X X X
5 X X X X X X
If you want to check if thePlayer is only in the diagonal indexes of the array, you can use a single for loop.
public boolean diagonal(char[ ][ ] theBoard, char thePlayer) {
boolean result = false;
int x; // This will tell you the coordinates of thePlayer if found on theBoard
for(int i = 0; I < theBoard.length; i++)
if (thePlayer == theBoard[i][i]) {
result = true;
// Add if you want to know coordinates of the player
x = i;
}
return result;
}
In my opinion, it's easier to use a for loop for things like this. The while loop is essentially the same thing implemented differently, but in this situation the for loop looks cleaner and easier to follow. In the end, it's up to you to decide which one is easier for you to implement.