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;
}
}这是我主要课程中我不明白的代码:
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() );,但我不明白的部分是:
"%-" + maxlength + "s %-5s %5s\n"看起来
%-5s在汽车名称( (cars.getStyle()),cars.name())和“速度”cars.name之间更改选项卡的宽度
%5s将选项卡的宽度在代码的“(cars.getClasss())”和“car类”之间更改。(输出如下:)
原始产出:

如果我把%-5s改为%-15s或什么的话,间距会在“威龙”和“速度”之间发生变化,但也会改变"Reventon“和”速度“之间的间隔。
我把威龙的名字改成了威龙,让它更长。
int maxlength = tuna.Veyronrrr.name().length();这是输出:

那么,这些代码是什么,他们为什么要做他们正在做的事情呢?
发布于 2012-01-24 03:32:49
%-5s的意思是“一个字符串,在至少五个字符的列中左对齐”,或者如果您愿意的话,“一个字符串,右填充空格,直到它至少有五个字符长”。
%5s是相同的,但右对齐而不是左对(即左填充而不是右填充)。
正如您所预期的那样,%-15s和%15s用于15个字符列,而不是5个字符列。
有关格式字符串语法的更多信息,请参见http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax。
发布于 2012-01-24 03:33:30
"%-" + maxlength + "s %-5s %5s\n"您可能知道,我们可以通过应用%2s或%-2s来缩进打印的内容。
"%-" + maxlength + "s意味着
%-(maxlength)s第一个字符串是否根据您提供的最大长度进行缩进,如果最大长度大于5,则打印材料不会缩进,因为您不能这样做
如果字符串实际长度为6个字符,则打印对齐至少6个字符的字符串。
请参阅dennis,以获得更清晰的%3s内容解释。
发布于 2012-01-24 04:10:27
代码要做的是格式化空格。
%-5s将添加额外的空格在单词的末尾完成5个字符。例如,如果您有:
System.out.format(".%-5s.","cat");输出将是
.cat .如果你有
%5s它将在单词之前添加空格,以完成5个字符。因此,有一个类似的例子:
System.out.format(".%5s.","cat");输出将是
. cat.https://stackoverflow.com/questions/8981649
复制相似问题