如何检查java中的二维数组中是否存在一对值

时间:2017-06-04 16:37:34

标签: java arrays

我有一个这种形式的二维数组:

int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};

我想检查programmaticaly是否有一对值{j,k} 存在于我的二维数组moves上。

6 个答案:

答案 0 :(得分:5)

for(int i = 0; i < 8; i++)
    {
        if(moves[i][0] == j && moves[i][1] == k)
        {
            //Executable code
        }
    }

答案 1 :(得分:5)

使用java 8,你可以写下这个内容:

int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
        {-1, -2}, {-2, 1}, {-2, -1}};

int [] t= {2,1};
boolean found = Arrays.stream(moves).anyMatch(m->Arrays.equals(m,t));

答案 2 :(得分:4)

您可以使用增强的for循环执行此操作:

boolean exists = false;
for (int[] move : moves) {
    if (move[0] == i && move[1] == j) {
        exists = true;
        break;
    }
}

如果exists数组中存在true对,则在循环结束时变量{i, j}设置为moves;否则,exists仍为false

答案 3 :(得分:3)

for (int x = 0; x < moves.length; ++x) {
    if (moves[x] != j) {
        continue;
    }

    for (int y = 0; y < moves[x].length; ++y) {
        if (moves[x][y] == k) {
            return true;
        }
    }
}

return false;

答案 4 :(得分:3)

    int[][] moves;
    moves = new int[][] { { 1, 2 }, { 1, -2 }, { 2, 1 }, { 2, -1 }, { -1, 2 }, { -1, -2 }, { -2, 1 }, { -2, -1 } };
    int n = 1;
    int m = 2;
    boolean found = false;
    for (int i = 0; i < moves.length; i++) {
        for (int j = 0; j < moves[0].length; j++) {
            if (moves[i][j] == n) {
                if (j < 1 && moves[i][j + 1] == m) {
                    found = true;
                    break;
                }
            }
        }
    }
    if (found) {
        System.out.println(String.format("[%d , %d] found", n, m));
    } else {
        System.out.println(String.format("[%d , %d] not found", n, m));
    }

答案 5 :(得分:2)

int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};

for(int j = 0; j < moves.length; j++){
    for(int k = 0; k < moves[j].length; k++){
        if(moves[j][k] != 0){
            System.out.println("Exist");
        }
    }
}

如果要检查特定索引更改moves[j][k]到您想要的索引。或者,如果您想比较两个值,

变化:

if(moves[j][k] != 0){

要:

if(moves[j] == 44 && moves[k] == 44){

如果您想要返回truefalse而不是打印可以使用的内容:

return true;

或者如果您想要返回特定索引中的值而不是打印可以使用的内容:

return moves[j][k];