gpt4 book ai didi

java - 有人可以向我解释这段 Java 代码(使用 System.out.format 格式化输出)吗?

转载 作者:行者123 更新时间:2023-11-29 07:16:39 27 4
gpt4 key购买 nike

枚举:

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.name()) 和“速度” (cars.getStyle() ), 而

%5s

更改代码中“速度”和“汽车等级”(cars.getClasss()) 部分之间制表符的宽度。(输出如下所示:)

原始输出:

enter image description here

现在,如果我将 %-5s 更改为 %-15s 或其他内容,“Veyron”和“Speed”之间的间距会发生变化,但它也会更改“Reventon”和它是“Speed” ".

我将 Veyron 的名称更改为 Veyronrrr 以使其更长。

int maxlength = tuna.Veyronrrr.name().length();

这是输出:

enter image description here

那么这些代码是什么,它们为什么要这样做?

最佳答案

%-5s 表示“一个字符串,在至少五个字符的列中左对齐”,或者如果您愿意,“一个字符串,用空格右填充直到至少五个字符长”。

%5s 相同,但右对齐而不是左对齐(即左填充而不是右填充)。

如您所料,

%-15s%15s 用于 15 个字符的列,而不是 5 个。

有关格式字符串语法的更多信息,请参阅 http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax .

关于java - 有人可以向我解释这段 Java 代码(使用 System.out.format 格式化输出)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8981649/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com