所以我的任务是编写一个可以创建两个矩阵的程序,然后将它们加在一起。我必须询问矩阵1的长度和高度,然后询问矩阵2的长度和高度。我在这里做了:
Scanner keyboard = new Scanner(System.in);
int length1, height1, length2, height2;
System.out.println("Welcome to the matrix adder program");
System.out.println(" ");
System.out.println("Please enter the length of the first matrix");
length1 = keyboard.nextInt();
System.out.println("Please enter the height of the first matrix");
height1 = keyboard.nextInt();
System.out.println("Please enter the length of the second matrix");
length2 = keyboard.nextInt();
System.out.println("Please enter the height of the second matrix");
height2 = keyboard.nextInt();
int[][] a = new int[length1][height2];
int[][] b = new int[length2][height2];
然后我需要输入矩阵1第1行,第1列,第1行,第2列等的值,直到它满足数组的尺寸。所以我把
for (int i = 1; i < length1 + 1; ++i)
{
for (int j = 1; j < height1 + 1; ++j)
{
System.out.println("Please enter a value for matrix 1 space "+ i + "," + j);
a[i][j] = keyboard.nextInt();
}
}
这就是我在线程&#34; main&#34;中得到错误异常的地方。 java.lang.ArrayIndexOutOfBoundsException:2 在MaxtrixAddition.main(MaxtrixAddition.java:32)
需要输出如下内容:
Please enter a value for matrix 1 space 1, 1
4
Please enter a value for matrix 1 space 1, 2
1
Please enter a value for matrix 1 space 2, 1
8
Please enter a value for matrix 1 space 2, 2
7
Please enter a value for matrix 2 space 1, 1
1
Please enter a value for matrix 2 space 1, 2
3
Please enter a value for matrix 2 space 2, 1
2
Please enter a value for matrix 2 space 2, 2
4
我需要做些什么才能摆脱这个错误?
答案 0 :(得分:0)
我希望我明白你想做什么。
阵列从位置0开始。
所以你的代码片段应该是:
for (int i = 0; i < length1; ++i)
{
for (int j = 0; j < height1 ; ++j)
{
System.out.println("Please enter a value for matrix 1 space "+ i + "," + j);
a[i][j] = keyboard.nextInt();
}
}