猿问

查看 int[][] 是否包含特定值

我有两个整数值'a'和'b'


我还有一个名为“keys”的 int[][]。它包含数字值,例如 { 0, 1 } 和 { 1, 2 }


我将如何查看'keys'是否包含a,b的组合?


到目前为止我已经尝试过:


if (keys.contains({a, b}){

    break;

}

这在 {a,b} 处给了我一个非法的表达式开始错误


慕田峪9158850
浏览 162回答 3
3回答

鸿蒙传说

我建议转换int[][]为List<List<Integer>>然后您可以使用该contains方法检查组合int[][] arr = {{1,2},{3,4}};&nbsp; &nbsp; List<Integer> check = Arrays.asList(1,2);&nbsp; &nbsp; List<List<Integer>> keys = Arrays.stream(arr)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(i->Arrays.stream(i).boxed().collect(Collectors.toList()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toList());&nbsp; //[[1, 2], [3, 4]]&nbsp; &nbsp; System.out.println(keys.contains(check));&nbsp; &nbsp; &nbsp;//true

江户川乱折腾

public boolean contains(int a, int b, int[][] keys){&nbsp; &nbsp; for (int i = 0; i < keys.length; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (keys[i][0] == a && keys[i][1] == b)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return false;}

月关宝盒

由于您的数组是 2*2,因此您可以执行此操作来检查匹配项。&nbsp; &nbsp; &nbsp; &nbsp; int a[][] = new int[100][100];&nbsp; &nbsp; &nbsp; &nbsp; int keyToCompare = 10;&nbsp; &nbsp; &nbsp; &nbsp; int valueToCompare = 20;&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0;i<a.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(a[i][0] == keyToCompare && a[i][1] == valueToCompare ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //match found&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答