Tableau avec la console java

Bonjour,

je veux afficher les donner dans un tableau en java console. Genre un tableau réelle avec les dimension pour chaque case.comment le faire svp?

merci

1 réponse

  1. Bonjour à toi !

    Il te faut faire une double boucle récursive
    Saches que un écran étant en 2D, tu ne pourras pas afficher des tableaux à plus de 2 dimensions

    Supposons que ton tableau s'appelle tab

    int i;
    int j;
    
    System.out.print(" ");
    for(i = 0; i < tab[0].length; i++)
    {
      System.out.print(" " + i);
    }
    System.out.println();
    System.out.print(" ");
    for(i = 0; i < tab[0].length; i++)
    {
      System.out.print("--");
    }
    System.out.println();
    
    for(i = 0; i < tab.length; i++)
    {
      System.out.print(i + "|");
      for(j = 0; j < tab[i].length; j++)
      {
        System.out.print(tab[i][j] + "|");
      }
      System.out.println();
      System.out.print(" ");
      for(j = 0; j < tab[i].length; j++)
      {
        System.out.print("--");
      }
      System.out.println();
    }
    


    A savoir que tu pourrais avoir des décalages si tu as des valeurs > 9, auquel cas il faudrait passer par le logarithme base 10 pour afficher le bon nombre de tirets...

    En espérant que cela t'aide et que tu comprennes !
    0
    1. Modérateur
      Bonjour,

      Ton affichage est tout bizarre.

      Exemple :
      String[][] tab = {{"Hello", "Toto"}, {"Bim","World!"}};

        0 1
       ----
      0|Hello|Toto|
       ----
      1|Bim|World!|
       ----

      Pour que cela soit joli, il faudrait dans une premier temps calculer la taille de chaque colonne.

      Exemple :
      public static void print(String[][] datas) {
          int height = datas.length, width = datas[0].length;
          int[] columnLengths = new int[width];
          for (int h = 0; h < height; h++) {
              for (int w = 0; w < width; w++) {
                  columnLengths[w] = Math.max(columnLengths[w], datas[h][w].length());
              }
          }
          int lineLength = width + 1;
          for (int columnLength : columnLengths) {
              lineLength += columnLength;
          }
          String line = "";
          for (int length = 0; length < lineLength; length++) {
              line += '-';
          }
          System.out.println(line);
          for (int h = 0; h < height; h++) {
              System.out.print('|');
              for (int w = 0; w < width; w++) {
                  System.out.print(datas[h][w]);
                  for (int s = datas[h][w].length(); s < columnLengths[w]; s++) {
                      System.out.print(' ');
                  }
                  System.out.print('|');
              }
              System.out.println();
              System.out.println(line);
          }
      }

      --------------
      |Hello|Toto  |
      --------------
      |Bim  |World!|
      --------------
      0