public class Homework2 {
public static void main(String[] args){
int num1 = (int) (Math.random()*(10-3+1)+3);
int num2 = (int) (Math.random()*(10-3+1)+3);
double[][] doubMatrix1 = new double[num1][num2];
double[][] doubMatrix2 = new double[num1][num2];
double[][] doubMatrix3 = new double[num1][num2];
doubMatrix1 = getdoubMatrix(num1,num2);
doubMatrix2 = getdoubMatrix(num1,num2);
doubMatrix3 = addMatrices(doubMatrix1, doubMatrix2, num1, num2);
printDoubMatrix("First matrix", doubMatrix1);
printDoubMatrix("Second matrix", doubMatrix2);
printDoubMatrix("Result of adding", doubMatrix3);
doubMatrix2 =transposeMatrix(num1,num2);
}
public static double[][] getdoubMatrix(int num1,int num2){
double[][] tempArray = new double[num1][num2];
for(int i = 0;i < tempArray.length;i++)
for(int j = 0;j < tempArray[i].length;j++)
{
tempArray[i][j] = Math.random() * (100);
}
return tempArray;
}
public static double[][] addMatrices(double[][] doubMatrix1, double[][] doubMatrix2,int num1,int num2)
{
double[][] tempArray = null;
if(doubMatrix1.length == doubMatrix2.length)
if(doubMatrix1[0].length == doubMatrix2[0].length)
{
tempArray = new double[num1][num2];
for(int i = 0; i< doubMatrix1.length;i++)
for(int j = 0; j< doubMatrix1[i].length;j++ )
{
tempArray[i][j] = doubMatrix1[i][j] + doubMatrix2[i][j];
}
}
else
{
return tempArray = new double[0][0];
}
return tempArray;
}
public static void printDoubMatrix(String text,double[][] doubMatrix1){
System.out.println(text);
for(int i = 0; i< doubMatrix1.length;i++)
for(int j = 0; j< doubMatrix1[i].length;j++ )
System.out.printf("%f\n", doubMatrix1[i][j]);
}
public static double[][] transposeMatrix(int num1, int num2){
double[][] tempArray = new double[num2][num1];
for(int i = 0;i < tempArray.length;i++)
for(int j = 0;j < tempArray[i].length;j++)
{
tempArray[i][j] = tempArray[j][i];
System.out.printf("%f\n", tempArray[i][j]);
}
return tempArray;
}
}
我在运行这个程序时遇到问题,没有错误,但是当我运行它时,它说数组索引超出范围,问题出在转置方法上,谁能告诉我如何解决这个问题?