在线程" main"中的Blockquote异常java.lang.ArrayIndexOutOfBoundsException:3 at twoDArray.sumTwoDim(twoDArray.java:11) at twoDArray.main(twoDArray.java:61)
Java编程新手。试图运行此代码并不断收到此错误。这段代码基本上是创建带有随机数的2d数组,并尝试将其旋转到右侧,左侧和翻转。我不在这个部分但我只是想确保代码实际打印正确的数组但我不知道该怎么做。
class twoDArray
{
public static int sumTwoDim (int [][] intMatrix)
{
int sum = 0;
for (int i = 0; i< intMatrix.length; i++)
{
for (int j = 0; j<intMatrix[0].length;i++)
{
sum += intMatrix[i][j];
}
}
return sum;
}
public static void printMatrix( int [][] intMatrix)
{
for (int i = 0; i< intMatrix.length; i++)
{
for (int j = 0; j<intMatrix[0].length;i++)
{
if (intMatrix[i][j]<10)
System.out.print(" ");
System.out.print(intMatrix[i][j]+ " ");
}
System.out.println();
}
}
public static int[][] rotateRight(int[][] intMatrix)
{
int [][] matrix = new int[3][4];
int [][] rotateMatrix = new int[intMatrix[0].length] [intMatrix.length];
for(int i = 0; i <intMatrix.length; i++)
{
for(int j = 0; j <intMatrix.length; j++)
{
rotateMatrix[i][j] = intMatrix[j][i];
}
}
return rotateMatrix;
}
public static void main(String[] args)
{
System.out.println("Hello world!");
int[][] matrix = new int[3][4];
int val = 5;
for(int i = 0; i < 3; i++)
for(int j = 0; j < 4; j++)
matrix[i][j] = val++;
int sum = sumTwoDim(matrix);
System.out.println("The sum of all values in matrix 1 is " + sum);
int[][] matrix2 = new int[5][3];
val = 2;
for(int i = 0; i<5; i++)
for(int j = 0; j<3; j++)
matrix2[i][j] = val++;
sum = sumTwoDim(matrix2);
System.out.println("The sum of all values in matrix 2 is " + sum);
printMatrix(matrix2);
printMatrix(rotateRight(matrix2));
}
}