Formatted array printing
I am trying to print a 2D array by walking through it with a nested for loop inside the loop.
char[][] largeArray = {{'&','&','^','#','@','@','@','@','&','*','*','*'},
{'#','&','&','^','@','@','@','@','*','*','*','*'}}
for (int r = 0; r < 2; r++)
{
for (int c = 0; c < 12; c++)
{
System.out.print(largeArray[r][c]);
}
}
What it prints is one line of everything inside this array
is there a way to print the first line of this array (everything in the first parenthesis) then the next line or the next parenthesis? I don't want extra space between the first line and the second line. so I can't just useSystem.out.println();
Any ideas?
source to share
You need to print a new line after printing each line:
for(int r = 0; r < 8; r++)
{
for(int c = 0; c < 12; c++)
{
System.out.print(largeArray[r][c]);
}
System.out.println(); // Add this outside the inner loop
}
You can also use a method Arrays.toString
to print your array to avoid using nested loops, for example:
for(int r = 0; r < 2; r++) {
System.out.println(Arrays.toString(largeArray[r]));
}
Also, to make your code look good, you can use an extended for-loop instead of the old loop to avoid indexing the array like this:
for (char[] arr: largeArray) {
System.out.println(Arrays.toString(arr));
}
source to share