I am currently trying to print out a table on java but am having a hard time get
ID: 3870705 • Letter: I
Question
I am currently trying to print out a table on java but am having a hard time getting it to display. I know how to display a table of numbers like:
1....23.... 45
6 .....78 ....9
5...... 8 .....39
but what i cant figure out is how to print out a table with titles. for example
...........Height.. Weight ...Age
Rod..... 70 .........210 .........31
Tod...... 67.... ......195......... 23
Bob ......74......... 231 ......36
I am looking for an example that'll point me in the right direction so i can better understand it.
The periods are just used for spacing to give a better representation of what I am looking to achieve. I had to put them there because it kept taking the spaces off and bunching everything together
Explanation / Answer
I hope the following code helps, comment if you have an doubt
public class Tester {
public static void main(String[] args) {
String heading = "Name";
String heading1 = "Height";
String heading2 = "Weight";
String heading3 = "Age";
//- specifies the left alignment if we remove the - sign then the text is right aligned to the table
// 20 specifies the spacing between variables
//printf function is used to perform this task
System.out.printf( "%-20s %-20s %-20s %-20s %n", heading, heading1, heading2, heading3);
String name= "Rod";
int height=70;
int weight= 210;
int age= 31;
System.out.printf( "%-20s %-20s %-20s %-20s %n", name, height, weight, age);
}
}
Output:
Name Height Weight Age
Rod 70 210 31
Screenshot is not uploading in which it is aligned properly.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.