-4

I wrote this code.

public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.println("Please enter the rows \"then\" columns of the first array: ");
        int a = console.nextInt();
        int b = console.nextInt();
        int[][] arr1 = new int[a][b];
        System.out.println("Please enter the rows \"then\" columns of the second array: ");
        int c = console.nextInt();
        int d = console.nextInt();
        int[][] arr2 = new int[c][d];
        if (b != c) {
            System.out.println("these two matrices can't be multiplied!!");
        } else {
            int[][] mult = new int[a][c];
            System.out.println("Please enter the elements of the first array : ");
            for (int i = 0; i < a; i++) {
                for (int j = 0; j < b; j++) {
                    arr1[i][j] = console.nextInt();
                }
            }
            System.out.println("Please enter the elements of the second array : ");
            for (int i = 0; i < c; i++) {
                for (int j = 0; j < d; j++) {
                    arr2[i][j] = console.nextInt();
                }
            }
            int sum = 0;
            for (int i = 0; i < a; i++) {
                for (int j = 0; j < d; j++) {
                    for (int k = 0; k < c; k++) {
                        sum += arr1[i][k] * arr2[k][j];
                        mult[i][j] = sum;
                    }
                    sum = 0;
                }

            }
            for(int i=0;i<a;i++){
                for(int j=0;j<d;j++) {
                    System.out.print(mult[i][j] + "  ");
                }
                System.out.println("");
            }
      }
    }
}

and when I run it, it says java.lang.ArrayIndexOutOfBoundsException.

I don't know why, Thanks for helping.

PM 77-1
  • 11,712
  • 18
  • 56
  • 99
  • 1
    Please post the full stack trace. Please read: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Turing85 Mar 13 '20 at 21:56
  • 1
    Please see https://ericlippert.com/2014/03/05/how-to-debug-small-programs/. – ruakh Mar 13 '20 at 21:57
  • This looks like great opportunity to learn how to use debugger. Most IDEs provide debugging tools, for instance in case of Eclipse see https://www.vogella.com/tutorials/EclipseDebugging/article.html. – Pshemo Mar 13 '20 at 21:57

1 Answers1

0

From what I see, here might be the problem: int[][] mult = new int[a][c], it should be new int[a][d]

P/s: Would be nicer if you can format the first part of your code

Nghia.xlee
  • 11
  • 1
  • 1