如何在2D数组上用foreach循环表示我的for循环?

时间:2018-05-13 13:30:18

标签: java multidimensional-array foreach

public static boolean doit(int[][] a, int b){
    for(int i=0; i<a.length; i++){
        for (int j = 0; j < a[i].length; j++)
        {
            if(a[i][j] ==b) {
                return true;
            }
        }
    }
    return false;
}

所以基本上我想使用ForEach循环来检查数组是否包含int b,但我不确定如何使用它。

public static boolean doitTwo(int[][] a, int b){
    for(c :a){
        for ( d:a){
              if(a[c][d] ==b) {
                return true;
            }
        }
    }

}

1 个答案:

答案 0 :(得分:1)

几乎就在那里,但是当内部循环应该使用a时,你在两个循环中迭代c。此外,当您迭代值而不是像这样的索引时,您不需要索引数组(就像您使用a[c][d]一样),因为您已经掌握了值。

public static boolean doitTwo(int[][] a, int b){
    for(int[] c : a){
        for (int d : c){
              if(d ==b) {
                return true;
            }

    }

}

我还为你的for循环添加了类型,因为它们可以推断出来并不是绝对必要的,但我更喜欢在Java中显式。

第一个for循环c : a接受并迭代其值。因为它是一个2D数组,所以每个元素都是一维数组!然后迭代该1D数组,1D数组的每个值都是int。

伪代码示例:

# Original 2D array which is an array, containing arrays of ints. i.e. int[][]
x = [[1, 2, 3], [4, 5, 6];

for (a : x) {
  # at this point on the first iteration, a = [1,2,3]. i.e. int[]
  for (b : a) {
    # at this point on the first iteration, b = 1. i.e. int
  }
}