我需要维数组的总和.......... 如何添加二维数组的总和,我完成了这个,但当我尝试添加标记[i] [j]时,我无法实现...
import java.util.Scanner;
public class TwoDimArray {
static int i, j;
public static void main(String[ ] args) {
int [ ][ ] marks = new int [4][4];
Scanner sc = new Scanner(System.in);
for (i = 1; i < marks.length ; i ++) {
System.out.println ("Enter marks of student "+i);
for ( j = 1; j < marks[i].length ; j++) {
System.out.println ("Subject "+j);
marks [i][j] = sc.nextInt();
}
}
for ( i = 1; i < marks.length ; i++) {
for ( j = 1; j < marks[i].length ; j++){
System.out.print (marks[i][j]+" ");
}
}
}
}
output:
Enter marks of student 1
Subject 1
45
Subject 2
48
Subject 3
47
Enter marks of student 2
Subject 1
52
Subject 2
56
Subject 3
54
Enter marks of student 3
Subject 1
65
Subject 2
66
Subject 3
75
45 48 47 52 56 54 65 66 75
*/
我想要总和[i] [j],我怎么能加上它的总和 科目,请解释科目总结...
答案 0 :(得分:0)
非常简单。首先是一些评论:
static int i, j;
不知道你为什么要这样做。只需在for-loop中声明它们。i
和j
执行任何操作,请使用foreach循环:for (int[] marksFromStudent : marks) {...
现在代码。我添加了一些代码来显示学生总数:
int[][] marks = getMarksFromScanner(); //the question is not about this part; might as well omit it.
int total = 0;
for (int i = 0; i < marks.length; i++) {
int studentTotal = 0;
for (int mark : marks[i])
studentTotal += mark;
System.out.println("student " + i + " has a total of " + studentTotal + " points");
total += studentTotal;
}
System.out.println("The whole class scored " + total + " points");
或没有学生总和的简单版本:
int[][] marks = getMarksFromScanner(); //the question is not about this part; might as well omit it.
int total = 0;
for (int[] studentMarks : marks)
for (int mark : studentMarks)
total += mark;
System.out.println(total);