我有一个需要打印很多内容的toString,包括一个包含多个条目的Arraylist。这些条目必须用新行分隔。这是我正在使用的toString代码:
@Override
public String toString() // Displays the info for a class
{
return getCourseId() + "\n" + getCourseName() + "\n" + getCourseCode()
+ "\n" + "\n" + "Instructor" + "\n" + "-------------------------"
+ "\n" + Instructor.toString() + "\n" + "\n" + "Student Roster"
+ "\n" + "-------------------------" + "\n" + roster;
}
名单会打印,但所有条目都在括号和逗号的同一行中。
我的教练坚持认为toString是自包含的,所以我在toString中的所有东西都必须留在那里。
名单打印如下:
@Override
public String toString() // Displays the info for a person in order
{
return getPersonId() + "\t" + getLastName() + "\t" + getFirstName()
+ "\t" + getMajor() + "\t" + getGpa();
}
目前,我得到的输出如下:
10000
College Algebra
MATH 101
Instructor
-------------------------
X00009876 Jones Jane Associate Professor Mathematics
Student Roster
-------------------------
[X00000002 Smith Sally History 2.98, X00000003 Adams Amanda Civil Engineering 3.7, X00000005 Turner Thomas Nursing 2.34]
但我希望它看起来像这样:
10000
College Algebra
MATH 101
Instructor
-------------------------
X00009876 Jones Jane Associate Professor Mathematics
Student Roster
-------------------------
X00000002 Smith Sally History 2.98
X00000003 Adams Amanda Civil Engineering 3.7
X00000005 Turner Thomas Nursing 2.34
任何建议都将不胜感激。谢谢!
答案 0 :(得分:4)
试试这个:
String rosterStr = roster.stream()
.map(r -> r.toString())
.collect(Collectors.joining("\n"))
将获取名单中每个值的字符串,然后将其与换行符连接
答案 1 :(得分:1)
我不确定你究竟在问什么,但我建议使用StringBuilder类,如下所示:
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
//You haven't provided much info about your ArrayList, customise this accordingly
for (Object o : ArrayList<Object>) {
sb.append(o.toString() + " ");
}
sb.setLength(sb.length() - 1);
return getCourseId() + "\n" + getCourseName() + "\n" + getCourseCode()
+ "\n" + "\n" + "Instructor" + "\n" + "-------------------------"
+ "\n" + Instructor.toString() + "\n" + "\n" + "Student Roster"
+ "\n" + "-------------------------" + "\n" + sb.toString();
}