Created
February 22, 2021 12:45
-
-
Save knockshore/16fa242cdc97f18af5f28f3aad2870cd to your computer and use it in GitHub Desktop.
Tabular printing using Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
/** | |
* | |
* @author karti | |
*/ | |
public class Table { | |
public static int tableWidth = 100; | |
public static void printColumns(String[] cols, int[] lengths) { | |
int ctr = 0; | |
printLine(lengths); | |
printTabular(new String[][] { cols }, lengths); | |
printLine(lengths); | |
} | |
public static void printLine(int[] lengths) { | |
System.out.print("+"); | |
for (int l : lengths) { | |
System.out.print(fill(l, '-')); | |
System.out.print("+"); | |
} | |
System.out.println(); | |
} | |
public static void printTabular(String[][] data, int[] lengths) { | |
// get a row | |
for (String[] row : data) { | |
int lineCtr = 0; | |
String[][] wrappedLines = new String[row.length][]; | |
int ctr = 0; | |
for (String cell : row) { | |
String[] wrapped = wrap(cell, lengths[ctr++]); | |
wrappedLines[lineCtr++] = wrapped; | |
} | |
int max = 0; | |
for (String[] wcells : wrappedLines) { | |
max = Math.max(max, wcells.length); | |
} | |
for (int i = 0; i < max; i++) { | |
int cctr = 0; | |
System.out.print("|"); | |
for (String[] wcells : wrappedLines) { | |
if (i < wcells.length) | |
System.out.print(pad(wcells[i], lengths[cctr])); | |
else | |
System.out.print(fill(lengths[cctr])); | |
cctr++; | |
System.out.print("|"); | |
} | |
System.out.println(); | |
} | |
} | |
// get wrapped arr for all the cells | |
// get max length | |
// write cascading line from all the cells | |
} | |
public static String pad(String s, int l) { | |
if (l == s.length()) return s; | |
char[] c = s.toCharArray(); | |
c = Arrays.copyOf(c, l); | |
Arrays.fill(c, s.length(), l - 1, ' '); | |
return new String(c); | |
} | |
public static String fill(int l) { | |
return fill(l, ' '); | |
} | |
public static String fill(int l, char f) { | |
char[] c = new char[l]; | |
Arrays.fill(c, f); | |
return new String(c); | |
} | |
public static String[] wrap(String line, int length) { | |
int c = line.length() / length | |
+ ((line.length() % length) > 0 ? 1 : 0); | |
if (c == 0) return new String[] { line }; | |
String[] lines = new String[c]; | |
for (int i = 0; i < c; i++) { | |
if ((i + 1) * length > line.length()) { | |
lines[i] = line.substring(i * length); | |
break; | |
} | |
lines[i] = line.substring(i * length, ((i + 1) * length)); | |
} | |
return lines; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment