Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to output two columns to the console in Java?

Tags:

java

As the title says, is there an easy way to output two columns to the console in Java?

I'm aware of \t, but I haven't found a way to space based on a specific column when using printf.

like image 611
James Avatar asked Mar 31 '09 03:03

James


People also ask

How do you print to console in Java?

print(): print() method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console. The next printing takes place from just here.

Which method is used to display output on console in Java program?

The methods used for writing console output are print(), println() and write().

What is the use of \t in Java?

What does \t mean in Java? This means to insert a new tab at this specific point in the text. In the below example, "\t" is used inside the println statement. It is similar to pressing the tab on our keyboard.


1 Answers

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); 
like image 100
erickson Avatar answered Sep 21 '22 10:09

erickson