repl.it
@Dexter1997/

Textual Table View

Java

This program prints out a table.

fork
loading
Files
  • Main.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

class Main {
  private static List<List<String>> table; 

  public static void main(String[] args) {
    initTable();
    int spacing = 3;
    printTable(spacing);
  }

  private static void initTable() {
    List<String> row1 = Arrays.asList("Name", "Klaus Ulbrecht", "Dieter", "Ursula");
    List<String> row2 = Arrays.asList("Sex", "male", "male", "female");
    List<String> row3 = Arrays.asList("Age", "12", "14", "16");
    table = Arrays.asList(row1, row2, row3);
  }

  private static void printTable(int spacing) {
    List<Integer> maxLengths = findMaxLengths();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < table.get(0).size(); i++) {
      for (int j = 0; j < table.size(); j++) {
        String currentValue = table.get(j).get(i);
        sb.append(currentValue);
        for (int k = 0; k < (maxLengths.get(j) - currentValue.length() + spacing); k++) {
          sb.append(' ');
        }
      }
      sb.append('\n');
    }

    System.out.println(sb);
  }

  private static List<Integer> findMaxLengths() {
    List<Integer> maxLengths = new ArrayList<>();
    for (List<String> row : table) {
      int maxLength = 0;
      for (String value : row) {
        if (value.length() > maxLength) {
          maxLength = value.length();
        }
      }
      maxLengths.add(maxLength);
    }
    return maxLengths;
  }
}