2012-12-15 78 views
0
public void calculatePercentage(int exam[][]) 
    { 
     int perc = 0; 
     for (int i = 0; i < examen.length; i++) 
     { 
      for (int[] score : exam) 
       perc += score; 
      perc /= exam.length; 
     } 
    } 

你好, 我真的被困在这一个。我想创建一个新的方法calculatePercentages给出参数exam [] []。双数组考试包含3行元素。该方法所要做的就是简单地计算每一行的总和。答案可能很简单,但我不知道该怎么做。 对于单个阵列,我想的代码是:双阵列操作单阵列

double perc = 0; 
    for(int score : exam) 
    { 
      perc += score; 
    } 
    perc /= (exam.length); 
    return perc; 

考试[] []可能看起来像:

| 10 12 18 5 3 | | 12 3 5 15 20 | | 20 15 13 11 9 |

输出百分比[]谨:

{48,55,68}百分比[]中的每一个元素是1行考试的元件的[]

+1

显示示例输入和示例输出,因为它根本不清楚。 –

+0

是的,它不清楚,为什么方法的名称是calculatePercentage,如果它只是总结它? – Amar

+0

见上面,我输入了一个可能的输入和输出 – STheFox

回答

3

双阵列考试保持3行元件。该方法所要做的就是简单地计算每一行的总和。

该名称没有任何意义,但它做你想做的事情。

public int[] calculatePercentage(int exam[][]) { 
    int[] sums = new int[exam.length]; 
    for (int i = 0; i < exam.length; i++) { 
     int sum = 0; 
     for (int j = 0; j < exam[i].length; j++) { 
       sum += exam[i][j]; 
     } 
     sums[i] = sum; 
    } 
    return sums; 
} 

另外一个双阵列将是double[],你正在谈论二维INT阵列int[][]

EDIT

Pshemo指出较短的解决方案是可能的:

public int[] calculatePercentage(int exam[][]) { 
    int[] sums = new int[exam.length]; 
    for (int i = 0; i < exam.length; i++) { 
     for (int j = 0; j < exam[i].length; j++) { 
       sums[i] += exam[i][j]; 
     } 
    } 
    return sums; 
} 

甚至只是

public int[] calculatePercentage(int exam[][]) { 
    int[] sums = new int[exam.length]; 
    for (int i = 0; i < exam.length; i++) 
     for (int j = 0; j < exam[i].length; j++) 
       sums[i] += exam[i][j]; 
    return sums; 
} 

但我仍然更喜欢第一个,因为它的可读性。

+1

+1,但你不需要临时'sum'变量,因为你已经有'sums [i]'在开始时为0。你可以只用'for(int j = 0; j Pshemo

+0

的确,2维数组,对不起, – STheFox

+0

@jlordo,第二行,是不是必须是int [] sums = new int [exam [i] .length];? 因为现在你将创​​建一个长度为5的数组,并且我需要在第二行中有3个长的 – STheFox

0
for (int i = 0; i < exam.length; i++) { 
     int sum = 0; 
     for (int j = 0; j < exam[i].length; j++) { 
      sum += exam[i][j]; 
     } 

    } 

使用总和对于每个

for (int x[] : exam) { 
     for (int y : x) { 

     sum += y; 
     } 
} 
+0

@无关紧要,你是对的。 –

+0

这是一个错误,谢谢 –

+0

谢谢mohammod hossain,但我已经有了一个解决方案。我很感激你。 – STheFox