Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

What is the significance of the print table Java?

Asked by Anil Jha Oct 12, 2022 1.2K views 1 answer
Share

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() {
    List row1 = Arrays.asList("Name", "Klaus Ulbrecht", "Dieter", "Ursula");
    List row2 = Arrays.asList("Sex", "male", "male", "female");
    List row3 = Arrays.asList("Age", "12", "14", "16");
    table = Arrays.asList(row1, row2, row3);
  }


  private static void printTable(int spacing) {
    List maxLengths = 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 List findMaxLengths() {
    List maxLengths = new ArrayList<>();
    for (List row : table) {
      int maxLength = 0;
      for (String value : row) {
        if (value.length() > maxLength) {
          maxLength = value.length();
        }
      }
      maxLengths.add(maxLength);
    }
    return maxLengths;
  }
}

Your answer

1 Answer

More Java discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Java Blogs

Guides, tips and career advice on Java from JanBask experts.