在2D数组中填充随机数以添加列/行 [英] Fill random numbers in a 2D array for column/row addition

查看:135
本文介绍了在2D数组中填充随机数以添加列/行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们刚接触Java并且进展缓慢。我在添加行和列之前尝试使用随机数填充2D数组。到目前为止,我可以创建数组,显示它,我很确定我有添加位排序。但是当我尝试用随机数填充它时,我得到了一个outofboundsexception。我哪里错了?

Hi folks new to Java and am making slow progress. I am trying to populate a 2D array with random numbers before I add the rows and columns. So far I can create the array, display it and I'm pretty sure I have the addition bit sorted. But I'm getting an outofboundsexception when I try to fill it with random numbers. Where am I going wrong?

public static void main(String[] args)
{
    //create the grid
    final int row = 9;
    final int col = 9;
    int [][] grid = new int [row][col];

    //fill the grid
    for (int i=0; i<grid.length; i++)
    grid[i][grid[i].length] = (int)(Math.random()*10);

    //display output
    for(int i=0;i<grid.length; i++)
    {
        for(int j=0; j<grid[i].length; j++)
        System.out.print(grid[i][j]+"");
        System.out.println();
    }

    int sum = 0;
    for (int i = 0; i < grid.length; i++) {
        System.out.println("This row sums up to: " + sum);


        for (int j = 0; j < grid[i].length; j++) {
            sum += grid[j][i];
        }
        System.out.println("This column sums up to: " + sum);
    }
}


推荐答案

grid[i][grid[i].length] = (int)(Math.random()*10);

这将是一个越界异常。数组 a 的最大索引是 a.length - 1 (因为数组是0索引的) - 你'尝试访问 a.length 的索引。这里 a grid [i]

This will be an out-of-bounds exception. The maximum index of an array a is a.length - 1 (since arrays are 0-indexed) -- you're trying to access an index of a.length. Here a is grid[i].

In无论如何,如果你想完全填充数组,你需要两个用于 -loops:

In any case, if you want to fill the array fully, you'll need two for-loops:

for (int i = 0; i < grid.length; i++) {
    for (int j = 0; j < grid[i].length; j++) {
        grid[i][j] = (int)(Math.random()*10);
    }
}

外部 -loop遍历2D数组 grid 中包含的所有1D数组,以及的内部 -loop用随机值填充这些内部1D数组中的每一个。

The outer for-loop loops over all the 1D arrays contained in the 2D array grid, and the inner for-loop fills each one of these inner 1D arrays with random values.

哦,还有最后一件事。计算总和时,在最里面的循环中,你有 sum + = grid [j] [i] 。您可能希望 i 成为数组索引, j 成为索引<$ c的数组的元素索引$ c>我,即 grid [i] [j]

Oh, and one last thing. When you calculate the sum, in the innermost loop, you have sum += grid[j][i]. You likely want i to be the array index and j to be the element index of the array at index i, i.e. grid[i][j].

请注意,如果您没有写入数组(例如打印或查找总和),您也可以使用Java的增强获取 -loop:

Also note that if you're not writing to the array (e.g. printing or finding the sum) you can use Java's enhanced for-loop as well:

int sum = 0;

for (int[] row : grid)
    for (int n : row)
        sum += n;

它略显冗长,也许更清晰。

It's slightly less verbose and perhaps more legible.

这篇关于在2D数组中填充随机数以添加列/行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆