How to print a two dimensional array?

you can use the Utility mettod. Arrays.deeptoString();

 public static void main(String[] args) {
    int twoD[][] = new int[4][]; 
    twoD[0] = new int[1]; 
    twoD[1] = new int[2]; 
    twoD[2] = new int[3]; 
    twoD[3] = new int[4]; 

    System.out.println(Arrays.deepToString(twoD));

}

Something like this that i answer in another question

public class Snippet {
    public static void main(String[] args) {
        int [][]lst = new int[10][10];

        for (int[] arr : lst) {
            System.out.println(Arrays.toString(arr));
        }
    }

}

public void printGrid()
{
   for(int i = 0; i < 20; i++)
   {
      for(int j = 0; j < 20; j++)
      {
         System.out.printf("%5d ", a[i][j]);
      }
      System.out.println();
   }
}

And to replace

public void replaceGrid()
{
   for (int i = 0; i < 20; i++)
   {
      for (int j = 0; j < 20; j++)
      {
         if (a[i][j] == 1)
            a[i][j] = x;
      }
   }
}

And you can do this all in one go:

public void printAndReplaceGrid()
{
   for(int i = 0; i < 20; i++)
   {
      for(int j = 0; j < 20; j++)
      {
         if (a[i][j] == 1)
            a[i][j] = x;
         System.out.printf("%5d ", a[i][j]);
      }
      System.out.println();
   }
}

Tags:

Java