2017-06-04 45 views
2

2维阵列上存在的一对值我有形式的2D阵列:如何检查是否在Java

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

+0

你说的'{J,K的意思}'?你的意思是类似的值,比如'{j,j}',还是你想搜索任何一对输入值? –

+0

任何一对整数 –

+1

欢迎来到堆栈溢出!请参考[游览](http://stackoverflow.com/tour),环顾四周,并阅读[帮助中心](http://stackoverflow.com/help) ,特别是[如何做我问一个好问题?](http://stackoverflow.com/help/how-to-ask)和[我可以问什么主题?](http://stackoverflow.com/help/on-topic) 。 从第二个链接中:“提出作业帮助的问题必须包括您迄今为止解决问题所做的工作摘要,并描述您解决问题的难度。” –

回答

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

+1

谢谢工作。 –

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){ 

注意:如果你想返回truefalse,而非打印的东西

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

你可以使用:

return true; 

或者如果你想返回特定指数鼠的值她比打印东西,你可以使用:

return moves[j][k]; 
4
for(int i = 0; i < 8; i++) 
    { 
     if(moves[i][0] == j && moves[i][1] == k) 
     { 
      //Executable code 
     } 
    } 
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; 
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)); 
+1

这当然有最明确的意图,并且是最干净的解决方案。 – Novaterata

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)); 
    }