我是Java编程的初学者。我创建了2D数组,生成随机数来填充数组。
但现在我需要分别计算行和列的总和,并使用方法将值存储在以1D数组格式化的单独表中...
这是我到目前为止所做的:
import java.util.*;
import java.math.*;
public class Q42 {
public static void main(String[] args) {
//create the grid
final int rowWidth = 4;
final int colHeight = 5;
Random rand = new Random();
int [][] board = new int [rowWidth][colHeight];
//fill the grid
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = rand.nextInt(10);
}
}
//display output
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
//System.out.println();
}
System.out.println();
} //end of main
public static int[] sumTableRows(int[][] table)
{
int rows = table.length;
int cols = table[0].length;
int[] sum = new int[rows];
for(int x=0; x<rows; x++)
for(int y=0; y<cols; y++)
sum[x] += table[x][y];
return sum;
}
} //end of class Main
答案 0 :(得分:0)
所以如果我理解正确的话,这就是你想要做的: 你有一个带有随机值的二维数组。你想要总结每一行中的所有值并放入一个变量。简单。你就是这样做的:
public static int[] sumTableRows(int[][] table)
{
int rows = table.length;
int cols = table[0].length;
int[] sum = new int[rows];//make an array for sums
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++){//iterate over all vars in the table array
int temp = table[i][j];//take value in point (i,j)
sum[i] += temp;//sum it in sum[i].
}
}
return sum; //return the 1D array
}