Enum:
public enum tuna {
Veyron("Speed", "R1"),
Reventon("Speed", "R3"),
MclarenF1("Speed", "R3");
public final String style;
public final String theclass;
tuna(String thestyle, String theclasss){
style = thestyle;
theclass = theclasss;
}
public String getStyle(){
return style;
}
public String getClasss(){
return theclass;
}
}
This is the code in my main class that I don’t understand:
int maxlength = tuna.Veyron.name().length();
for( tuna cars : tuna.values() ) {
System.out.format( "%-" + maxlength + "s %-5s %5s\n", cars.name(), cars.getStyle(), cars.getClasss() );
But the part that I don’t understand (well, a little) is this:
"%-" + maxlength + "s %-5s %5s\n"
It seems
%-5s
changes the width of the tab in between the name of the car (cars.name()) and “Speed” (cars.getStyle()), while
%5s
changes the width of the tab between “Speed” and “Class of the car (cars.getClasss()) part of the code. (Output seen below:)
Original Output:

Now if I change %-5s to %-15s or something, the spacing changes in between “Veyron” and “Speed”, but it also changes that of “Reventon” and it’s “Speed”.
I changed the name of Veyron to Veyronrrr to make it longer.
int maxlength = tuna.Veyronrrr.name().length();
This is the output:

So I what are these pieces of code, and why do they do what they’re doing?
%-5smeans “a string, left-aligned in a column of at least five characters”, or if you prefer, “a string, right-padded with spaces until it’s at least five characters long”.%5sis the same, but right-aligned instead of left-aligned (i.e., left-padded instead of right-padded).%-15sand%15s, as you’d expect, are for fifteen-character columns instead of five.For more information on the syntax of format strings, see http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax.