import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
int d1 = (int) (Math.random()*(10-3+1)+3);
int d2 = (int) (Math.random()*(10-3+1)+3);
double[][] doubMatrix1 = new double[d1][d2];
double[][] doubMatrix2 = new double[d1][d2];
double[][] doubMatrix3 = new double[d1][d2];
doubMatrix1 = getdoubMatrix(d1,d2);
doubMatrix2 = getdoubMatrix(d1,d2);
doubMatrix3 = addMatrices(doubMatrix1, doubMatrix2);
}
public static double[][] getdoubMatrix(int d1, int d2){
double[][] tempArray = new double[d1][d2];
for(int i =0; i <tempArray.length;i++ )
for(int j =0;j < tempArray[i].length;j++)
tempArray[i][j] = Math.random()*(10.0);
return tempArray;
}
public static double[][] addMatrices(double doubMatrix1[][], double doubMatrix2[][]){
for(int i = 0; i< doubMatrix1.length;i++)
for(int j = 0; j< doubMatrix1[i].length;j++ )
{
if(doubMatrix1[i][j] == doubMatrix2[i][j])
{
double[][] tempArray = new double[i][j];
}
else
{
return tempArray[0][0];
}
}
return tempArray;
}
}
我在 addMatrices 方法中的两个返回语句上都遇到错误,而且我认为我做得不对
这就是我应该为 addMatrices 方法做的事情
在addMatrices方法中,
· 检查第一维和第二维是否各为 2 维。 array 数组是相同的——如果它们不相同,则返回 0 X 0 2-dim。数组,否则执行以下操作;
· 为本地 2-dim 分配内存。与 2-dim 之一具有相同维度的数组。数组参数
· 将每个相应元素添加到参数 2-dim 中。数组并将结果存储在本地 2-dim 的相应元素中。数组(使用嵌套 for 循环)
· 返回本地 2 维。数组
最佳答案
public static double[][] addMatrices(double doubMatrix1[][],
double doubMatrix2[][]){
for(int i = 0; i< doubMatrix1.length;i++)
for(int j = 0; j< doubMatrix1[i].length;j++ )
{
if(doubMatrix1[i][j] == doubMatrix2[i][j])
{
double[][] tempArray = new double[i][j];
}
else
{
return tempArray[0][0];
}
}
return tempArray;
}
第一个问题是,在您的 else 部分中,您返回了一个 double 值。 ArrayElement,而返回类型定义为
数组的数组
。其次,您已在
if
内声明了您的tempArray
并在返回时在外部使用它。它在您的外部不可见如果
。在您的方法中、if 和 for 循环之外声明它。
需要进行主要修改:-
将 else 中的返回语句更改为:-
tempArray = new double[0][0];
并在 for 循环之外声明您的
tempArray
。
嗯,除了上面的问题还有很多。从逻辑上讲,您的 addMatrix
并未添加您的矩阵。我认为你应该检查该代码..
关于java - 比较二维数组然后将它们相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12885415/