2014-09-24 36 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);