I am a beginner in programming and I am currently learning how to build a responsive table in Java. I came across something that I think I need help to figure out with. Let me use an easy example to illustrate it.
I have 2 arrays,
String[] name = new String[] {"James","Tom","Rodriguez"};
Integer[] score = new Double[] {15,20,13};
and I want to transform them into something like this,
Name Score
James 15
Tom 20
Rodriguez 13
I am using "\\t" and somehow successful in making them aligned but then when I add some name that is a bit longer the output become like this.
Name Score
James 15
Tom 20
Rodriguez Fernandes 13
My friend told me to use System.out.printf
but I am not sure how to apply it with arrays, especially when the data is large. Could someone help me how to better format a table something like this?
In order to do this, you first need to find the string
with maximum length and append (max length minus string length) spaces while printing all the other names, eg:
public static void print(String[] names, Integer[] score){
//Find the name with max length
int maxLength = Arrays.stream(names)
.mapToInt(String::length)
.max().getAsInt() + 2;
//Now, start the printing
System.out.println(String.format("%1$-" + maxLength + "s", "Name") + "Score");
for(int i=0 ; i<names.length ; i++){
System.out.println(String.format("%1$-" + maxLength + "s", names[i]) + score[i]);
}
}
Here, I have added 2
to the max length to show two empty spaces after name with maximum length. This can be called from main
, eg:
public static void main(String[] args) throws Exception{
print(new String[]{"James","Tom","Rodriguez"}, new Integer[]{15,20,30});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.