比较一维数组中的3个元素

时间:2012-02-25 19:27:13

标签: java arrays compare

如何检查一维数组的3个元素是否等于特定值?

背景:我正在尝试检查一个井字游戏(noughts and crosses)的胜利者。换句话说,检查3x3网格中的任何线条是否扁平化为单维数组。

以下是我尝试的代码:

尝试1:

switch ()
{
    case board[(6&3&0) || (7&4&1)]: case board[7&4&1]: case board[8&5&2]: case board[0&1&2]: case board[3&4&5]: case board[6&7&8]: case board[6&4&2]: case board[8&4&0]:
    System.out.println("Equal to x")
    break;
}

尝试2:

if (board[7] , board[4] , board[1] == 'X')
system.out.println("Equal");

尝试3:

if ( board[6&3&0] == 'X'  || board[7&4&1] == 'X' || board[8&5&2] == 'X' || board[0&1&2] == 'X' || board[3&4&5] == 'X' || board[6&7&8] == 'X' || board[6&4&2] == 'X' || board[8&4&0] == 'X') {
    System.out.println("Equal to x");
}else if
( board[6&3&0] == 'O'  || board[7&4&1] == 'O' || board[8&5&2] == 'O' || board[0&1&2] == 'O' || board[3&4&5] == 'O' || board[6&7&8] == 'X' || board[6&4&2] == 'O' || board[8&4&0] == 'O'){
    System.out.println("Equal to o!");
}

2 个答案:

答案 0 :(得分:4)

你的tic-tac-toe的“游戏场”看起来像这样:

0 1 2
3 4 5
6 7 8

0-8是char[]数组中的索引:

marks = new char[9];

检查我们是否连续三个'x':

'x' == marks[0] == marks[3] == marks[6] // a vertical row
'x' == marks[0] == marks[1] == marks[2] // a horizontal row
'x' == marks[0] == marks[4] == marks[8] // a diagonal row

这应该让你开始。

编辑:这将编译:

boolean win = marks[0] == 'x' && marks[3] == 'x' && marks[6] == 'x';

答案 1 :(得分:1)

你的电路板可能有一个二维数组:

board = new char[3][3]

并且您想知道是否可以将其映射到单个维度。答案是肯定的。只需在头脑中对方格进行编号:

012
345
678

声明

board = new char[9]

并在代码中使用这些索引。