编写一个Java程序,找出矩阵每行的总和,并附带一个示例。或者编写一个Java程序来计算给定矩阵或多维数组中每一行的总和。
在此Java矩阵行求和示例中,我们声明了一个具有随机值的3x3 SumOfRows_arr整数矩阵。接下来,我们使用for循环遍历SumOfRows_arr矩阵的元素。在for循环内,我们计算SumOfRows_arr矩阵行的总和。
public class SumOfMatrixRows {
public static void main(String[] args) {
int i, j, sum;
int[][] SumOfRows_arr = {{15, 25, 35}, {45, 55, 65}, {75, 85, 95}};
for(i = 0; i < SumOfRows_arr.length; i++)
{
sum = 0;
for(j = 0; j < SumOfRows_arr[0].length; j++)
{
sum = sum + SumOfRows_arr[i][j];
}
System.out.println("\nThe Sum of Matrix Items in " + i + " row = " + sum);
}
}
}
Java矩阵行求和输出
The Sum of Matrix Items in 0 row = 75
The Sum of Matrix Items in 1 row = 165
The Sum of Matrix Items in 2 row = 255
Java程序查找矩阵每行总和的示例2
此Java矩阵每行求和代码与上述代码相同。但是,此Java代码允许用户输入行数、列数和矩阵元素。请参考C程序查找矩阵中每一行的总和文章以了解for循环的迭代执行。
import java.util.Scanner;
public class SumOfMatrixRows {
private static Scanner sc;
public static void main(String[] args) {
int i, j, rows, columns, sum = 0;
sc= new Scanner(System.in);
System.out.println("\n Enter Matrix Rows and Columns : ");
rows = sc.nextInt();
columns = sc.nextInt();
int[][] SumOfRows_arr = new int[rows][columns];
System.out.println("\n Please Enter the Matrix Items : ");
for(i = 0; i < rows; i++) {
for(j = 0; j < columns; j++) {
SumOfRows_arr[i][j] = sc.nextInt();
}
}
for(i = 0; i < SumOfRows_arr.length; i++)
{
sum = 0;
for(j = 0; j < SumOfRows_arr[0].length; j++)
{
sum = sum + SumOfRows_arr[i][j];
}
System.out.println("\nThe Sum of Matrix Items in " + i + " row = " + sum);
}
}
}
