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... }
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].
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.
Java provides multiple ways to print a 2d array, for example nested for-loop, for-each loop, Arrays. deepToString() method, etc.
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 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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With