if ((board[x][x] && board[x + 1][x + 1] && board[x + 2][x + 2]) == 'Y') {
playerWins = true;
}
为什么我不能用&&这里呢?
你想要这个:
if (board[x][x] == 'Y' && board[x + 1][x + 1] == 'Y' && board[x + 2][x + 2] == 'Y') {
playerWins = true;
}
&&
只能用于布尔表达式的连接。
你的代码假设了某种分布规则,比如(x && y) == z
等价于(x == z) && (y == z)
。在英语中,您可以这样表述"如果x和y都是z",但是编程语言(和形式逻辑)没有这样的定义。
Java逻辑运算符仅对布尔值执行操作。因此,任何逻辑运算符的两个操作数都必须是布尔值。在你的代码中,board[x][y]是char类型的,因此它抛出一个异常。你需要将它与其他布尔值进行比较。棋盘[x + 1][x + 1]也一样。(手机打字)
Java的条件求值与其他语言(如C, c++)不同。
尽管循环条件(if、while和for中的退出条件Java和c++都需要布尔表达式,代码如if(a = 5)会在Java中导致编译错误,因为没有隐式从int到boolean的窄化转换。
详情请参阅以下连结:https://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2B
您不能将这些要求值的表达式与'&&'或'||'连接起来,因为它们不会被求值为布尔值,而是在本例中被求值为字符。
但是,你可以这样做:
if (board[x][x] == 'Y' && board[x + 1][x + 1] == 'Y' && board[x + 2][x + 2] == 'Y') {
playerWins = true;
}
或者这样:
/*so this methods check if the board has a different value than 'Y', so it returns false immediately without going over the other positions, otherwise if the value was equal to Y at all positions the if statement wont be accessed,
you will exit the for-loop & return true; You're main method must store the boolean value returned not more */
public static boolean winGame(PARAMS p) { //you can give it the 2d array as a parameter for example..
for(int x = 0; x < value; x++) { // you specify the value according to your board
if(board[x][x] != 'Y') {
return false;
}
return true;
}