Is there an easy way to output two columns to the console in Java?
Solution 1:
Use the width and precision specifiers, set to the same value. This will pad strings that are too short, and truncate strings that are too long. The '-' flag will left-justify the values in the columns.
System.out.printf("%-30.30s %-30.30s%n", v1, v2);
Solution 2:
i did it without using Formatter class as :
System.out.printf("%-10s %-10s %-10s\n", "osne", "two", "thredsfe");
System.out.printf("%-10s %-10s %-10s\n", "one", "tdsfwo", "thsdfree");
System.out.printf("%-10s %-10s %-10s\n", "onsdfe", "twdfo", "three");
System.out.printf("%-10s %-10s %-10s\n", "odsfne", "twsdfo", "thdfree");
System.out.printf("%-10s %-10s %-10s\n", "osdne", "twdfo", "three");
System.out.printf("%-10s %-10s %-10s\n", "odsfne", "tdfwo", "three");
and output was
osne two thredsfe
one tdsfwo thsdfree
onsdfe twdfo three
odsfne twsdfo thdfree
osdne twdfo three
odsfne tdfwo three
Solution 3:
Late answer but if you don't want to hardcode the width, how about something that works like this:
public static void main(String[] args) {
new Columns()
.addLine("One", "Two", "Three", "Four")
.addLine("1", "2", "3", "4")
.print()
;
}
And displays:
One Two Three Four
1 2 3 4
Well all it takes is:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Columns {
List<List<String>> lines = new ArrayList<>();
List<Integer> maxLengths = new ArrayList<>();
int numColumns = -1;
public Columns addLine(String... line) {
if (numColumns == -1){
numColumns = line.length;
for(int column = 0; column < numColumns; column++) {
maxLengths.add(0);
}
}
if (numColumns != line.length) {
throw new IllegalArgumentException();
}
for(int column = 0; column < numColumns; column++) {
int length = Math
.max(
maxLengths.get(column),
line[column].length()
)
;
maxLengths.set( column, length );
}
lines.add( Arrays.asList(line) );
return this;
}
public void print(){
System.out.println( toString() );
}
public String toString(){
String result = "";
for(List<String> line : lines) {
for(int i = 0; i < numColumns; i++) {
result += pad( line.get(i), maxLengths.get(i) + 1 );
}
result += System.lineSeparator();
}
return result;
}
private String pad(String word, int newLength){
while (word.length() < newLength) {
word += " ";
}
return word;
}
}
Since it won't print until it has all the lines, it can learn how wide to make the columns. No need to hard code the width.