To print a one-dimensional data structure like ArrayList
in two dimensions you are going to have to set a fixed line size. This is actually a very similar problem as loading pixels stored in linearly stacked memory to a two-dimensional image. Check the linked article for more details about this problem.
You need nested loops to achieve this behaviour, which you already have (fillWithSpaces()
(containing a loop) is called from inside another loop). So, change fillWithSpaces()
to something like this:
private static String fillWithSpaces(String cadena) {
String line = "";
for (int i = 0; i < cadena.length(); i++) {
line += cadena.charAt(i);
line += " ";
}
return line;
}
This code can also be simplified using a utility called StringJoiner
to join strings and characters with a delimiter:
private static String fillWithSpaces(String cadena) {
StringJoiner joiner = new StringJoiner(" ");
for (int i = 0; i < cadena.length(); i++) {
joiner.add(cadena.charAt(i));
}
return joiner.toString();
}
Also, you need to jump to a new line at the end of the outer loop. This can be done by changing System.out.print()
to System.out.println()
, which will automatically output a new line.
Check this article by Daniel Shiffman for an extensive explanation of the same problem in a different context (under Pixels, pixels, and more pixels): https://processing.org/tutorials/pixels/