【发布时间】:2017-03-12 16:02:10
【问题描述】:
if ((board[x][x] && board[x + 1][x + 1] && board[x + 2][x + 2]) == 'Y') {
playerWins = true;
}
为什么我不能使用 && 和 ||在这里?
【问题讨论】:
-
board变量是什么类型?
if ((board[x][x] && board[x + 1][x + 1] && board[x + 2][x + 2]) == 'Y') {
playerWins = true;
}
为什么我不能使用 && 和 ||在这里?
【问题讨论】:
board变量是什么类型?
您不能将这些表达式与 '&&' 或 '||' 连接起来,因为它们不会被评估为布尔值,但在这种情况下会被评估为字符。
但是,您可以这样做:
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;
}
【讨论】:
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;
}
&& 只能用于连接布尔表达式。
您的代码假定了某种分布规则,例如 (x && y) == z 等同于 (x == z) && (y == z)。在英语中,您可以这样说“如果 x 和 y 都是 z”,但编程语言(和形式逻辑)没有这样的定义。
【讨论】:
Java 逻辑运算符仅对布尔值执行操作。所以任何逻辑运算符的两个操作数都需要是布尔值。在您的代码中, board[x][y] 是 char 类型,因此它会引发异常。您需要将其与某些东西进行比较或具有其他布尔值。 板[x + 1][x + 1] 相同。 (手机输入)
【讨论】: