如何在二维数组中打印行和列?

时间:2013-11-06 03:15:59

标签: java arrays

我正在尝试让这个数组显示以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]); 

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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]);