提问人:HGSu 提问时间:8/3/2023 更新时间:8/3/2023 访问量:31
对齐 toString 中的文本
Align text in toString
问:
我想保持此代码中的顺序,但我不知道如何使学位的价值低于大学的价值
@Override
public String toString() {
return "Education" +
" " + System.getProperty("line.separator") +
year+ " "+ university + System.getProperty("line.separator")+
" "+ degree ;
}
我想要什么
2023 UniversityExample
Bachelor of somthing
但看起来像这样:
2023 UniversityExample
Bachelor of somthing
或者像这样:
2019 to 2023 UniversityExample
Bachelor of somthing
答:
0赞
Hardik Uchdadiya
8/3/2023
#1
您可以在方法中使用 \t,如下所示
@Override
public String toString() {
return "Education" +
"\t" + System.getProperty("line.separator") +
year+ "\t"+ university + System.getProperty("line.separator")+
"\t"+ degree ;
}
评论
0赞
HGSu
8/3/2023
它已经安排了代码,但不是我想要的,谢谢。
0赞
Hardik Uchdadiya
8/4/2023
好吧,你到底想要什么?从问题来看,您似乎只是想要正确的格式,这是您正在寻找的其他东西吗?
0赞
Reilas
8/3/2023
#2
可以使用 String#formatted 方法创建固定宽度的字符串。
格式说明符的完整列表可以在格式化程序 JavaDoc 页面上找到。
return
"Education%n".formatted()
+ "%-17s%s%n".formatted(year, university)
+ "%17s%s".formatted("", degree);
以下是一些示例输出,
Education
2023 UniversityExample
Bachelor of somthing
Education
2019 to 2023 UniversityExample
Bachelor of somthing
评论
0赞
HGSu
8/3/2023
谢谢,但这给了我一个错误。
评论
toString()