As you can see in below code, I am trying to add two (2-D integer ARRAYS),I know that variable (c) in the first method is a reference to the array , why can not I return that array or it's reference , Can I return 2-D array in general ,how?
import java.util.*;
public class Matrix_Addition {
public static int sum (int[][]a,int[][]b){
int[][]c=new int [a.length][b[1].length];
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++)
c[i][j]=a[i][j]+b[i][j];
}
return c;
}
public static void display(int[][]a){
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++)
System.out.println(a[i][j]);
}
}
public static void main(String[] args) {
int[][]a={{1,2,3},
{4,5,6},
{7,8,9}};
int[][]b={{9,8,7}
,{6,5,4},
{3,2,1}};
int[][]c=sum(a,b);
display(a);
display(c);
}
}
c is an array/matrix but you try to return an int, try
public static int[][] sum (int[][]a,int[][]b) {
In general you should specificy in which line java tells you the error appears when asking a question.
Hope it helps!
Since you have declared c as a 2-D array (int[][]c=new int [a.length][b[1].length])
Your sum method returns int and you are trying to return int 2-D array so it is giving you an error that incompatible types: int[][] cannot be converted to int
You should change return type to your sum method from int to int[][].
public static int[][] sum (int[][]a,int[][]b){
您可以使用与输入相同的类型:
public static int[][] sum(int[][] a, int[][] b)
Change you main function this line of code..
int[][]c=sum(a,b);
with
int c=sum(a,b);
and all the downline code like this...
display(a);
display(b);
System.out.println(c);
this will works. because if you see your add()
function definition
public static int sum (int[][]a,int[][]b){.....} // return type is int not int[][].
Reason : Return type of
sum(int[][], int[][])
isint
notint[][]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.