-2

Is there a way to print an ArrayList like a Excel spreadsheet ?

example My code is this:

private static void printList() {
    for (int i = 0; i < matrizCuadrada.size(); i++) {
        System.out.print(fillWithSpaces(matrizCuadrada.get(i).getValor()));;
    }
}

private static String fillWithSpaces(String cadena) {
    int cantidadEspacios = 9 - cadena.length();
    for (int i = 0; i < cantidadEspacios; i++) {
        cadena += " ";
    }
    return cadena;
}
Martin Brisiak
  • 3,872
  • 12
  • 37
  • 51
sixGdie
  • 1
  • 3

1 Answers1

0

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/

D3PSI
  • 154
  • 2
  • 11