首页 > 解决方案 > 如何用二维数组上的 foreach 循环来表达我的 for 循环?

问题描述

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

}

标签: javamultidimensional-arrayforeach

解决方案


快到了,但是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采用 a 并迭代其值。因为它是一个二维数组,所以它的每个元素都是一个一维数组!然后迭代该一维数组,一维数组的每个值都是 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
  }
}

推荐阅读