gpt4 book ai didi

java - 计算不均匀二维数组中的列总和

转载 作者:行者123 更新时间:2023-12-01 18:30:17 25 4
gpt4 key购买 nike

我一直在通过一些免费的在线教程自学 Java,并挑战自己完成几乎所有的练习。我已经在这个问题上坚持了一个星期了,这让我发疯。我觉得我已经相当接近了,只是被构成不均匀列的不同数组长度绊倒了。

            public class Testing {
public static void main(String[] args) {
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };

int sum = 0;
int row = 0;
int col = 0;
int currentRow = 0;

while (currentRow < data.length) {
for (col = 0; col < data[currentRow].length; col++) {
sum = 0;
for (row = 0; row < data.length; row++) {
System.out.println(data[row][col]);
sum += data[row][col];
}
System.out.println("Sum: " + sum);
}
currentRow++;
}
}
}

最佳答案

如果您尝试计算行总和

似乎有一个循环太多了。您的 while 遍历第一个维度,而 for(row... 遍历第二个维度。因此,无需通过 for(row. ..尝试少用一个循环:

       public class Testing {
public static void main(String[] args) {
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };

int sum = 0;

for (int currentRow = 0; currentRow < data.length; currentRow++) {
sum = 0;
for (int col = 0; col < data[currentRow].length; col++) {
System.out.println(data[currentRow][col]);
sum += data[currentRow][col];
}
System.out.println("Sum: " + sum);
}
}
}

如果您尝试计算列总和

public class Testing {
public static void main(String[] args) {
int[][] data = { {3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
// get max length of a row == number of columns
int length = 0;
for (int r = 0; r < data.length; r++) {
int currLength = data[r].length;
if(currLength>length) length = currLength;
}
// create array for column sums
int[] sums = new int[length];
// fill array with zeros
Arrays.fill(sums, 0);
// sum up
for (int currentRow = 0; currentRow < data.length; currentRow++) {
for (int col = 0; col < data[currentRow].length; col++) {
System.out.println(data[currentRow][col]);
sums[col] += data[currentRow][col];
}
}
// print sums
for (int i = 0; i < sums.length; i++) {
System.out.println(i + ": " + sums[i]);
}
}
}

关于java - 计算不均匀二维数组中的列总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24518180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com