Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a two dimensional array?

Tags:

I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".

The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.

public void printGrid() {     System.out.println... } 
like image 832
user997462 Avatar asked Oct 16 '11 03:10

user997462


People also ask

How do you print a two dimension array?

public class Print2DArray { public static void main(String[] args) { final int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; for (int i = 0; i < matrix. length; i++) { //this equals to the row in our matrix. for (int j = 0; j < matrix[i].

How do I print a dimensional array?

To print the content of a one-dimensional array, use the Arrays. toString() method. To print the content of a a multi-dimensional array, use the Arrays. deepToString() method.

Can you print a 2D array in Java?

Java provides multiple ways to print a 2d array, for example nested for-loop, for-each loop, Arrays. deepToString() method, etc.


2 Answers

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));  } 
like image 51
Vidhya - Vidhyadharan Avatar answered Oct 14 '22 14:10

Vidhya - Vidhyadharan


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();    } } 
like image 41
COD3BOY Avatar answered Oct 14 '22 14:10

COD3BOY