简体   繁体   English

如何在2D数组上用foreach循环表达for循环?

[英]How can I express my for loop with a foreach loop on my 2D array?

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

So basically I want to use the ForEach loop, for checking if the array contains the int b , but I'm not sure how to use it. 因此,基本上我想使用ForEach循环来检查数组是否包含int b ,但是我不确定如何使用它。

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

}

Nearly there, but you're iterating over a in both loops when the inner loops should be using c . 快到了,但你遍历a在两个环路时,内循环应该使用c Also, when you are iterating over the values instead of the indexes like this, you don't need to index into the arrays (like you were doing with a[c][d] ), as you already have the values in hand. 另外,当您遍历值而不是像这样的索引时,您不需要索引到数组中(就像您使用a[c][d] ),因为已经有了值。

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

    }

}

I also added types to your for loops, not strictly necessary as they can be inferred, but I prefer being explicit in Java. 我还为您的for循环添加了类型,并非绝对必要,因为可以推断出它们,但是我更喜欢在Java中显式。

The first for loop c : a takes a and iterates over its values. 第一个for循环c : a接受a并对其值进行迭代。 As it's a 2D array, each of it's elements are a 1D array! 由于它是一个2D数组,因此每个元素都是一个1D数组! You then iterate over that 1D array and each values of the 1D array is int. 然后,您遍历该1D数组,并且1D数组的每个值都是int。

Example pseudocode: 伪代码示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM