总结在Java中每个行和列 [英] Summing up each row and column in Java
本文介绍了总结在Java中每个行和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
/*
* Programmer: Olawale Onafowokan
* Date: February 6, 2014
* Purpose: Prints the row and column averages
*/
class Lab4 {
public static void main(String[] args) {
int [][] scores = {{ 20, 18, 23, 20, 16 },
{ 30, 20, 18, 21, 20 },
{ 16, 19, 16, 53, 24 },
{ 25, 24, 22, 24, 25 }};
outputArray(scores);
}
public static void outputArray(int[][] array) {
int sum= 0;
int rowSize = array.length;
int columnSize = array[0].length;
System.out.println("rows=" + rowSize + "cols=" + columnSize);
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
sum += array[i][j];
}
System.out.println("Print the sum of rows = " + sum);
}
for (int i = 0; i < array.length; i++) {
sum = 0;
sum = sum + array[i][j];
// It is telling me the j can't be resolved
}
}
}
程序打印出:
rows=4cols=5
Print the sum of rows = 612
Print the sum of rows = 20358
Print the sum of rows = 652058
Print the sum of rows = 20866609
我不明白为什么它不正确地加起来的数字。我试图加起来每行和每列。我甚至不知道在哪里,这些数字的来源。
I don’t understand why it isn't adding up the numbers correctly. I am trying to add up each row and column. I am not even sure where these numbers are coming from.
推荐答案
下面是你的问题:
sum += sum + array[i][j];
之和+ = SUM +阵列[i] [j]的
相同总和=总和+总和+阵列[I] [J ]
(您添加总和的两倍的)
应该是:
总和=总和+阵列[I] [J];
或 之和+ =阵列[我] [ J];
如果你要打印的每张行仅的总和,重置之
到 0
有关外每次迭代 for循环
If you want to print the sum of each row only, reset your sum
to 0
for each iteration on outer for-loop
for (int i = 0; i < array.length; i++){
sum=0;
....
如果你要打印的每张列仅的总和,需要补充一点:
If you want to print the sum of each column only, you need to add this:
int[] colSum =new int[array[0].length];
然后在 for循环
添加
colSum[j]+=array[i][j];
所以最后你都会有这样的:
So finally you will have this:
int[] colSum =new int[array[0].length];
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
sum += array[i][j];
colSum[j] += array[i][j];
}
System.out.println("Print the sum of rows =" + sum);
}
for(int k=0;k<colSum.length;k++){
System.out.println("Print the sum of columns =" + colSum[k]);
}
这篇关于总结在Java中每个行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文