-3

I wrote code for adding two matrices with the help of two-dimensional arrays. But after running, it is showing a result with error [[I@6acbcfc0. If you know the meaning of [[I@6acbcfc0, then please describe it as well. Following is the code:

public static void main(String[] args) {
    
    Scanner sc = new Scanner (System.in);
    
    System.out.println("Enter dimensions: ");       
    int rows = sc.nextInt();
    int cols = sc.nextInt();
    
    int a[][] = new int [rows][cols];
    int b[][] = new int [rows][cols];
    
    System.out.println("Enter first matrix: ");     
    for (int i = 0; i<rows; i++) {
        for (int j = 0; j<cols; j++) {
            a[i][j] = sc.nextInt();
        }
    }
    
    System.out.println("Enter second matrix: ");        
    for (int i = 0; i<rows; i++) {
        for (int j = 0; j<cols; j++) {
            b[i][j] = sc.nextInt();
        }
    } 
    
    int c [][] = new int [rows][cols];
    
    for (int i = 0; i<rows; i++) {
        for (int j = 0; j<cols; j++) {
            c[i][j] = a[i][j] + b[i][j];
        }
    }
    
    System.out.println("Result is " + c);
    for(int i = 0; i<rows; i++) {
        for (int j = 0; j<cols; j++) {
            System.out.print(c[i][j] + " ");
        }
        System.out.println();
    }
}

}

and the output is

Enter dimensions: 
2 2

Enter first matrix: 

1 2

1 2

Enter second matrix: 

1 2

1 2

Result is [[I@6acbcfc0

2 4 

2 4 

Please help me in removing "[[I@6acbcfc" and if you find any mistake in my code, please correct it so that i can understand it further better. Thank you.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

2 Answers2

0

You are printing c using System.out.println("Result is " + c); so it is being added to output. Just remove that and you are good to go.

You can also try this to print 2D array.

System.out.println(Arrays.deepToString(c));

for printing normal array

System.out.println(Arrays.toString(c));
kelvin
  • 1,480
  • 1
  • 14
  • 28
0

Your problem is that you are executing

 System.out.println("Result is " + c);

where c is int [][]

Presumably you want the entire array to be printed out by thus, but this is not behavior that actually exists.

What you see printed is the result of c.toString(), which is not defined to be anything useful to you.

If you want the array content printed out, you'll have to write code to print it, element by element. Which, in fact, you have already done, immediately below.

for(int i = 0; i<rows; i++) {
    for (int j = 0; j<cols; j++) {
        System.out.print(c[i][j] + " ");
    }
    System.out.println();
}

So just remove the + c from the preceding println call.

J.Backus
  • 1,441
  • 1
  • 6
  • 6