Search code examples
javabluej

Array index out of bound exception for Maximum and minimum program


I was making a program to accept numbers in double dimensional array and find the greatest and lowest number. But when I enter mu inputs, it shows error in the 2nd if statement saying:

"Array index out of bound exception"

import java.util.Scanner;
public class DDA_MaxMin
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        int ar[][] = new int[4][4];
        int a,b,c=0,d=0;
        for(a=0;a<4;a++)
        {
            for(b=0;b<4;b++)
            {
                System.out.println("Enter the numbers in the matrix "+a+" "+b);
                ar[a][b]=in.nextInt();
            }
        }
        c=ar[0][0];
        d=ar[0][0];
        for(a=0;a<4;a++)
        {
            for(b=0;b<4;b++)
            if(c>ar[a][b])
            c=ar[a][b];
            if(d<ar[a][b])         
            d=ar[a][b];
        }
        System.out.println("The greatest number is "+d);
        System.out.println("The smallest number is "+c);
    }
}

Solution

  • The for loop without { will only be valid for next line or next statement.

    for(b = 0; b < 4; b++)
     if(c>ar[a][b])
        c=ar[a][b]
    

    after this b value is 4.

    and the if statement after that is out of the for loop hence the out of bounds exception.

    Enclose them in braces.

    for(a=0;a<4;a++)
        {
            for(b=0;b<4;b++){
            if(c>ar[a][b])
            c=ar[a][b];
            if(d<ar[a][b])         
            d=ar[a][b];
            }
        }