0

我试图让这个数组显示以 2x2 数组排列的 4 个值。到目前为止,我正在做的事情是数组越界错误。我怎样才能正确地做这个显示?

import java.util.Scanner;
import java.util.Random;



 public class GridPractice
{

public static void main(String[] args)
{
  //declarations
  Scanner in = new Scanner(System.in);
  Random  generator = new Random();
  int [][] grid;    //un-instantiated grid
  int size = 0; //number of rows and columns

  //get size of grid - no validation & instantiate
  System.out.print("Enter size of grid: ");
  size = in.nextInt();
  grid = new int[size][size];

   //fill grid with random number from 1..99
  System.out.println();
  for (int row=0; row<size; row++)
  {
     for (int col=0; col<size; col++)
     {
        grid[row][col] = generator.nextInt(100); //random numbers 0.99 - not 100

     }

   }

  System.out.printf("%2d\n", grid[size][size]); 
4

2 回答 2

0
for (int row = 0; row < size; row++) {
    for (int col = 0; col < size; col++) {
        System.out.printf("%2d ", grid[row][col]);
    }
    System.out.println();
}
于 2013-11-06T03:23:08.367 回答
0

尝试这个:

   for (int row = 0; row < size; row++) {
        for (int col = 0; col < size; col++) {
            System.out.print(grid[row][col] + " ");
        }
        System.out.println("");
    }

加上删除这一行,这是异常的罪魁祸首:

System.out.printf("%2d\n", grid[size][size]); 
于 2013-11-06T03:23:54.653 回答