user3182420
user3182420

Reputation: 21

Array Index out of Bound Exception while running the program to find largest of an array

Here is the code:Getting Array index out of Bound exception

class Max {
    public static void main(String args[]) {
        int a[][];
        Scanner src = new Scanner(System. in );
        System.out.println("Enter the no of rows");
        int rows = src.nextInt();
        a = new int[rows][5];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < 5; j++) {
                a[i][j] = src.nextInt();
            }
        }
        System.out.println("Array is");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print("  " + a[i][j]);
            }
            System.out.println();
        }
        int l = a[0][0];
        int i;
        for (i = 0; i < rows; i++)
            l = a[i][0];
        for (int j = 0; j < 5; j++)
            if (l < a[i][j])
                l = a[i][j];
        System.out.println("Max" + l);
    }
}

on run time it gives the following: Exception in thread "main" java.lang.Array index out of Bound Exception:3 at Max.main Max.java:33 Can Anyone suggest what is wrong in the code????

Upvotes: 0

Views: 290

Answers (2)

Mohsen Kamrani
Mohsen Kamrani

Reputation: 7457

Try this:

public static void main(String args[]) {
    int a[][];
    Scanner src = new Scanner(System. in );
    System.out.println("Enter the no of rows");
    int rows = src.nextInt();
    a = new int[rows][5];
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < 5; j++) {
            a[i][j] = src.nextInt();
        }
    }

    System.out.println("Array is");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < 5; j++) {
            System.out.print("  " + a[i][j]);
        }
        System.out.println();
    }
    int l = a[0][0];
    int i;
    for (i = 0; i < rows; i++) {
        l = a[i][0];
        for (int j = 0; j < 5; j++)
            if (l < a[i][j])
                l = a[i][j];
    }
    System.out.println("Max" + l);
}

Upvotes: 0

Nicolas Defranoux
Nicolas Defranoux

Reputation: 2676

You miss a { after the for (i = 0; i < rows; i++) so that the for (int j = 0; j < 5; j++) loop is inside the first one.

Without that, this gives:

for (i = 0; i < rows; i++)
  l = a[i][0];
// End of the for i loop, now i = rows. 
for (int j = 0; j < 5; j++)
  if (l < a[i][j])  // i = rows: bang.
    l = a[i][j];

Upvotes: 2

Related Questions