0
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.

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

}

1 Answer 1

1

Nearly there, but you're iterating over a in both loops when the inner loops should be using 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.

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.

The first for loop c : a takes a and iterates over its values. As it's a 2D array, each of it's elements are a 1D array! You then iterate over that 1D array and each values of the 1D array is 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
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

It works thank you, but can you explain why i have to use the first loop with an array and the second without?
@R.You The 2D array is basically an array of arrays, so when iterating through a 2D array, its elements are 1D arrays. Once you get to the second loop, you're iterating through a 1D array, so you're simply left with int values as elements.
I updated the answer with a more thorough explanation.
Thanks a lot, got it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.