问题
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);
}
}
回答1:
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.
来源:https://stackoverflow.com/questions/18839715/fill-random-numbers-in-a-2d-array-for-column-row-addition