【发布时间】:2014-12-26 13:09:01
【问题描述】:
我正在尝试计算二维数组中对角线之后的元素总和,但问题是总和始终为零,它不会改变答案。
我的代码中的错误在哪里以及如何修复它?
我尝试使用嵌套 for 循环,o 尝试使用一个 for 循环,但在这两种情况下,eanswer 仍然为 0。
这是我的代码:
package test8;
import java.util.Scanner;
public class Question2 {
private int row = 4;
private int col = 4;
private int[][] matrix;
public Question2(int trow, int tcol) {
this.row = trow;
this.col = tcol;
}
public Question2(int trow, int tcol, int[][] m) {
this.row = trow;
this.col = tcol;
this.matrix = m;
}
public int[][] fill() {
int[][] data = new int[row][col];
Scanner in = new Scanner(System.in);
for (int row = 0; row < data.length; row++) {
for (int col = 0; col < data[row].length; col++) {
System.out.println("enter the elementss for the Matrix");
data[row][col] = in.nextInt();
}
System.out.println();
}
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < data[row].length; col++) {
System.out.print(data[row][col] + " ");
}
System.out.println();
}
return data;
}
public int calculate(int[][] num) {
int sum = 0;
for (int row = 0; row < num.length; row++) {
//for (int col = row + 1; col < num[row].length; col++) {
// if(row == col){
System.out.println(row);
sum += num[row][row];
// }
//}
}
System.out.println("the sum is: " + sum);
return sum;
}
public static void main(String[] args) {
Question2 q2 = new Question2(3, 3);
int[][] ma = q2.fill();
q2.calculate(ma);
}
}
这是输出:
1 2 3
4 5 6
7 8 9
0
1
2
the sum is: 15
【问题讨论】:
-
您求和的数组很可能全是零,即不是您打印出来的那个。
-
@java dev 显示你的数组
-
好的,我将编辑我的问题并显示孔代码
标签: java for-loop sum multidimensional-array