2014-09-24 33 views
-2

我需要维数组的总和.......... 如何添加二维数组的总和,我做到这一点,但当我尝试添加标记[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

你有一个'INT sum',并且添加了标记它。 – Teepeemm 2014-09-24 12:22:33

+1

首先,数组以索引0开始,而不是1开始。 – Magnilex 2014-09-24 12:23:11

回答

0

它的漂亮si mple。首先一些意见:

  • static int i, j;不知道为什么你会想这样做。只需在for循环中声明它们即可。
  • ,因为你不ij比选择合适的标记之外做任何事情,使用foreach循环:for (int[] marksFromStudent : marks) {...
  • 第一数组索引是0,而不是1

而现在为码。香港专业教育学院增加了一些代码,也显示了学生总数:

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);