-1

I used the eclipse(2019-12) for Java programming.

When I ran below the program with any input, it shows

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:Index 0 out of bounds for length 0
at Array.inputArr(Array.java:21)
at App1.main(App1.java:6)

I don't know where the problem is.

My code as below:

Array.java

package App;
import java.util.*;
class Array
{
    int m, n;
    Scanner reader=new Scanner(System.in);
    void inputLen()
    {
        System.out.print("Please enter array row and column: ");
        m=reader.nextInt();
        n=reader.nextInt();
    }
    int[][] arr=new int[m][n];
    int i, j;
    void inputArr()
    {
        System.out.println("Please enter "+m+"*"+n+" array: ");
        for(i=0; i<m; i++)
            for(j=0; j<n; j++)
                arr[i][j]=reader.nextInt();
    }
    void sumColumn()
    {
        int[] colSum=new int[n];
        for(j=0; j<n; j++)
        {
            for(i=0; i<m; i++)
                colSum[j]+=arr[i][j];
            System.out.println("Column"+(j+1)+" sum="+colSum[j]);
        }
    }
}

App1.java

public class App1
{
    public static void main(String[] args)
    {
        Array matrix=new Array();
        matrix.inputLen();
        matrix.inputArr();
        matrix.sumColumn();
    }
}
Drox
  • 1
  • 1
  • 1
  • You create the array before `inputLen()` is called, so `m` and `n` are `0`, so you're creating a zero-length array. – Mark Rotteveel Feb 29 '20 at 09:01
  • Please also note that creating a Class with name `Array` is discouraged as it makes your code ambiguous. You should give a different name like `MyArray` or something like that. – Imtiaz Shakil Siddique Feb 29 '20 at 09:07

1 Answers1

2

When you create matrix : Array matrix=new Array(); m and n equals 0. your array :

int[][] arr=new int[0][0];

try this:

int[][] arr;
void inputLen()
    {
        System.out.print("Please enter array row and column: ");
        m=reader.nextInt();
        n=reader.nextInt();
        arr = new int[m][n];
    }
Abdullajon
  • 366
  • 3
  • 12