[java] How to print a two dimensional array?

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...
}

This question is related to java

The answer is


I am also a beginner and I've just managed to crack this using two nested for loops.

I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.

P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.

public static void printGrid() {
    for (int i = 0; i < moleGrid.length; i++) {
        for (int j = 0; j < moleGrid[0].length; j++) {
            if (j == 0 || j % (moleGrid.length - 1) != 0) {
                System.out.print(moleGrid[i][j]);
            }
            else {
                System.out.println(moleGrid[i][j]);
            }
         }
     }
}

Hope it helps!


more simpler approach , use java 5 style for loop

Integer[][] twoDimArray = {{8, 9},{8, 10}};
        for (Integer[] array: twoDimArray){
            System.out.print(array[0] + " ,");
            System.out.println(array[1]);
        }

You should loop by rows and then columns with a structure like

for ...row index...
  for ...column index...
    print

but I guess this is homework so just try it out yourself.

Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.


How about trying this?

public static void main (String [] args)
{
   int [] [] listTwo = new int [5][5];
    // 2 Dimensional array 
    int x = 0;
    int y = 0;
    while (x < 5) {
        listTwo[x][y] = (int)(Math.random()*10);

        while (y <5){
            listTwo [x] [y] = (int)(Math.random()*10);
            System.out.print(listTwo[x][y]+" | ");
            y++;                
        }
        System.out.println("");
        y=0;
        x++;
    }
}

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));
        }
    }

}

If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.

    int numDigits = (int) Math.log10(maxValue) + 1;
    if (numDigits <= 1) {
        numDigits = 2;
    }
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < matrix.length; i++) {
        int[] row = matrix[i];
        for (int j = 0; j < row.length; j++) {
            int block = row[j];
            buf.append(String.format("%" + numDigits + "d", block));
            if (j >= row.length - 1) {
                buf.append("\n");
            }
        }
    }
    return buf.toString();

Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.

public void printGrid(int[][] in){  
    for(int i = 0; i < 20; i++){  
        for(int j = 0; j < 20; j++){  
            if(in[i][j] == 1)  
                System.out.print('X' + "\t");
            else
                System.out.print(in[i][j] + "\t");
        }
        System.out.print("\n");
    }
}

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));

}

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

just for int array