-2

I am trying to find the max value of a 2D array in java.

 import java.util.*;

 public class ikiBoyutlu {

 public static void ikiBoyut(int[][]a){
    int eb= a[0][0];

    for(int i=0;i<a.length;i++){
        for(int j=0; j<(a[0].length);j++){
            if(a[i][j]>eb){
                eb=a[i][j];
            }

        }

    }
    System.out.println("The max value of array= "+ eb);
}

public static void main(String[] args){

    int a[][] ={{2,5,7,0,-6,28,43},{-96,45,3,21}};
    ikiBoyut(a);

}

}

But I get index out of range error. I wonder why?

Thanks!

3 Answers3

1

You're iterating over different nested arrays, while invariably watching i < a[0].

Your inner loop should be declared this way, instead:

for(int j=0; j<(a[i].length);j++)

and in your example the second inner array is smaller than the first. so when iterating through the second with the length of the first, it will definitely get out of the bounds ...

ernest_k
  • 39,584
  • 5
  • 45
  • 86
0

You have a two dimensional array, which is basically an array of arrays.

Your two two dimensional array effectively contains two arrays with different lengths.

Your second loop has the condition of

j<(a[0].length)

when it should be

j<(a[i].length)

Use the length of each array element.

MartinByers
  • 1,049
  • 1
  • 6
  • 15
0

You are testing the inner loop against a[0].length which is the length of the first array in your jagged multidimensional array (and longer than the second). Instead, use a[i].length - and you might also initialize eb with Integer.MIN_VALUE and use Math.max(int, int) instead of coding your own test. Like,

public static void ikiBoyut(int[][] a) {
    int eb = Integer.MIN_VALUE;
    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            eb = Math.max(eb, a[i][j]);
        }
    }
    System.out.println("The max value of array= " + eb);
}

This is also a place where you could potentially eliminate errors by using a for-each loop. For example,

public static void ikiBoyut(int[][] a) {
    int eb = Integer.MIN_VALUE;
    for (int[] arr : a) {
        for (int i : arr) {
            eb = Math.max(eb, i);
        }
    }
    System.out.println("The max value of array= " + eb);
}

And, in Java 8+, we can use lambdas to shorten it significantly. Like,

public static void ikiBoyut(int[][] a) {
    int eb = Stream.of(a).flatMapToInt(IntStream::of).max().orElse(Integer.MIN_VALUE);
    System.out.println("The max value of array= " + eb);
}
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226