【发布时间】:2014-11-25 17:36:53
【问题描述】:
我正在尝试添加用户输入的 4x4 矩阵的对角线,当我运行程序时, 我在数组中添加所有 4 个值的行给出了错误。
我没有正确添加它们吗?
import java.util.Scanner;
public class Set_9_P7_2 {
public static void main(String[] args) {
double x;
double[][] sumMajorDiagnol = new double[4][4];
System.out.println("Enter a 4-by-4 matrix row by row:");
Scanner input = new Scanner(System.in);
for (int i = 0; i < sumMajorDiagnol.length; i++) {
for (int j = 0; j < sumMajorDiagnol.length; j++) {
sumMajorDiagnol[i][j] = input.nextDouble();
}
}
x = sumMajorDiagnol[1][1] + sumMajorDiagnol[2][2] + sumMajorDiagnol[3][3] + sumMajorDiagnol[4][4];
System.out.println("The sum of the elements in the major diagnal is " + x);
}
}
我没有打印实际答案 4,而是收到此错误:
Enter a 4-by-4 matrix row by row:
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Set_9_P7_2.main(Set_9_P7_2.java:21)
指向这条线:
x = sumMajorDiagnol[1][1] + sumMajorDiagnol[2][2] + sumMajorDiagnol[3][3] + sumMajorDiagnol[4][4];
这不是你应该添加它们的方式吗?
【问题讨论】:
标签: java multidimensional-array add