【问题标题】:Add the individual columns and rows in a 2D Array and display in a 1D Array table?在 2D Array 中添加单独的列和行并显示在 1D Array 表中?
【发布时间】:2016-04-25 08:49:24
【问题描述】:

我是 Java 编程的初学者。我创建了生成随机数来填充数组的二维数组。

但现在我需要单独计算行和列的总和,并将值存储在一个单独的表格中,该表格使用一种方法格式化为一维数组...

这是我目前所拥有的:

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

【问题讨论】:

  • 似乎是什么问题?乍一看,您似乎做得很好。
  • @JohnSensebe 我不知道如何将值存储在使用方法格式化为一维数组的单独表中。
  • separate table formatted in a 1D 是什么意思?
  • 你认为sumTableRows 是做什么的?
  • @789 我必须以表格格式记录各个行和列的总和。我只是假设最好在方法中将该表格式化为一维数组。我该怎么做?

标签: java arrays random methods


【解决方案1】:

所以如果我理解正确,这就是你想要做的: 您有一个带有随机值的二维数组。你想总结每一行中的所有值并放入一个变量。简单。这就是你的做法:

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  
}

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2020-05-10
  • 2020-12-11
  • 2021-05-05
  • 2018-03-20
  • 2021-11-01
  • 2018-08-25
  • 2019-12-15
相关资源
最近更新 更多