Fill random numbers in a 2D array for column/row addition

一世执手 提交于 2019-12-04 17:09:15
grid[i][grid[i].length] = (int)(Math.random()*10);

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 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);
    }
}

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.

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].

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!