使用循环打印出二维数组中的行总和
Printing out the sum of rows in a 2D array using a loop
我想先打印出我的数组,然后打印出每一行的总和,在我的完整数组之后,使用嵌套的 for 循环。但是,在我的第一个嵌套 for 循环将值分配给我的二维数组之后,似乎没有发生任何其他事情。我希望它看起来像:
第一行的总和是:...
第二行的总和是……等等,直到最后一行。
这是我目前所拥有的。
我的代码:
public class RowsSum {
public static void main(String[] args) {
int num = 1;
int[][] nums = new int[5][3]; //declaring a 2D array of type int
for (int i = 0; i <= nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
num *= 2;
nums[i][j] = num;
System.out.print(nums[i][j] + "\t");
}//closing inner loop
System.out.println("");
}// closing nested for loop
int sum = 0;
int row = 0;
for (int i = 0; i <= nums.length; i++) { //second nested for loop
row++;
for (int j = 0; j < nums[0].length; j++) {
sum = sum + nums[i][j];
}//closing inner loop
System.out.println("The sum of the " + row + "is" + sum + "\t");
System.out.println("");
}// closing nested for loop
}// closing main method
}//closing class
您没有在遍历行之前将 sum 变量重新初始化为 0。此外,尚不清楚您的第二个双 for 循环试图用这段代码完成什么:
num *= 2;
nums[i][j] = num;
这段重复的代码实际上改变了数组中的值,您应该删除它,它会导致不必要的影响。
调整为:
for (int i = 0; i <nums.length; i++){ //second Outer loop
sum = 0;
for (int j = 0; j < nums[0].length; j++){
sum = sum + nums[i][j];
}//closing inner loop
System.out.println("The sum of row " + (i+1) + " is " + sum);
}
此外,嵌套的 for 循环实际上是内部循环而不是外部循环。
编辑:您实际上也在访问原始数组的边界之外,特别是在外循环中。你有这个:
for (int i = 0; i <= nums.length; i++)
改成这样:
for (int i = 0; i < nums.length; i++)
注意 <= 到 < 的小变化,它微妙但重要,因为数组在 java 中索引为 0,因此在长度为 5 的数组中,最大索引将为 4。
我想先打印出我的数组,然后打印出每一行的总和,在我的完整数组之后,使用嵌套的 for 循环。但是,在我的第一个嵌套 for 循环将值分配给我的二维数组之后,似乎没有发生任何其他事情。我希望它看起来像: 第一行的总和是:... 第二行的总和是……等等,直到最后一行。 这是我目前所拥有的。
我的代码:
public class RowsSum {
public static void main(String[] args) {
int num = 1;
int[][] nums = new int[5][3]; //declaring a 2D array of type int
for (int i = 0; i <= nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
num *= 2;
nums[i][j] = num;
System.out.print(nums[i][j] + "\t");
}//closing inner loop
System.out.println("");
}// closing nested for loop
int sum = 0;
int row = 0;
for (int i = 0; i <= nums.length; i++) { //second nested for loop
row++;
for (int j = 0; j < nums[0].length; j++) {
sum = sum + nums[i][j];
}//closing inner loop
System.out.println("The sum of the " + row + "is" + sum + "\t");
System.out.println("");
}// closing nested for loop
}// closing main method
}//closing class
您没有在遍历行之前将 sum 变量重新初始化为 0。此外,尚不清楚您的第二个双 for 循环试图用这段代码完成什么:
num *= 2;
nums[i][j] = num;
这段重复的代码实际上改变了数组中的值,您应该删除它,它会导致不必要的影响。
调整为:
for (int i = 0; i <nums.length; i++){ //second Outer loop
sum = 0;
for (int j = 0; j < nums[0].length; j++){
sum = sum + nums[i][j];
}//closing inner loop
System.out.println("The sum of row " + (i+1) + " is " + sum);
}
此外,嵌套的 for 循环实际上是内部循环而不是外部循环。
编辑:您实际上也在访问原始数组的边界之外,特别是在外循环中。你有这个:
for (int i = 0; i <= nums.length; i++)
改成这样:
for (int i = 0; i < nums.length; i++)
注意 <= 到 < 的小变化,它微妙但重要,因为数组在 java 中索引为 0,因此在长度为 5 的数组中,最大索引将为 4。