About this question
This program prints out a table in the console. Suggestions for improvements are welcome.
Example output
Name Sex Age
Klaus Ulbrecht male 12
Dieter male 14
Ursula female 16
You can test and modify the program here.
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
class Main {
private static List> table;
public static void main(String[] args) {
initTable();
int spacing = 3;
printTable(spacing);
}
private static void initTable() {
Listrow1 = Arrays.asList("Name", "Klaus Ulbrecht", "Dieter", "Ursula"); Listrow2 = Arrays.asList("Sex", "male", "male", "female"); Listrow3 = Arrays.asList("Age", "12", "14", "16"); table = Arrays.asList(row1, row2, row3);
}
private static void printTable(int spacing) {
ListmaxLengths = findMaxLengths();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < table> for (int j = 0; j < table> 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 ListfindMaxLengths() { ListmaxLengths = new ArrayList<>(); for (Listrow : table) { int maxLength = 0;
for (String value : row) {
if (value.length() > maxLength) {
maxLength = value.length();
}
}
maxLengths.add(maxLength);
}
return maxLengths;
}
}