对齐 toString 中的文本

问题描述 投票:0回答:2

我想保持这段代码中的顺序,但我不知道如何使 Degree 的值低于 University 的值

 @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   
java android text tostring text-alignment
2个回答
0
投票

你可以在方法中使用,像这样

@Override
public String toString() {
    
    return "Education" +
            "\t" + System.getProperty("line.separator") +
            year+ "\t"+ university + System.getProperty("line.separator")+
            "\t"+ degree ;
    
}

0
投票

您可以使用 String#formatted 方法创建固定宽度的字符串。

格式说明符的完整列表可以在 Formatter 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
© www.soinside.com 2019 - 2024. All rights reserved.