I’m trying to grid an output using the printf() statement.
The Strings are generated via a 2D array that is iterated with two for loops
example:
String[][] arr =
{
{"*", "2", "1", "*", "1"},
{"*", "2", "1", "*", "1"},
{"*", "2", "1", "*", "1"},
{"*", "2", "1", "*", "1"},
{"*", "2", "1", "*", "1"}
}
for(int i = 0; i < arr.length; i++)
{
for(int j = 0; j < arr[0].length; j++)
{
System.out.printf("%s", arr[i][j]);
}
}
I basically want the output just as it appears in the code (as a 5×5 grid) but the tutorials on formatting are not very easy to follow and most do not deal with this sort of format.
Ideally, the output should look like this:
* 2 1 * 1
* 2 1 * 1
* 2 1 * 1
* 2 1 * 1
* 2 1 * 1
My question is, besides how would I do this using the printf() characters, is will I come across any problems using these inside a nested for-loop? Also, I understand where the %s comes from, but any further symbol usage is beyond me. Could someone explain why they would use the symbol and characters they are using for this?
Thank you very much.
You need to add a
System.out.println();after yourinner loopends to print your next row in a newline: –For more details on various
format specifiersee this link: –