I'm a beginner in Java programming. I have created the 2D array that generates random numbers to fill the array.
But now I need to calculate the sum of the rows and columns individually and store the values in a separate table formatted in a 1D array using a method...
This is what I have so far:
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
Aucun commentaire:
Enregistrer un commentaire