我希望返回一个字符串,如下所示:
Josephine Blow (Associate Professor, Math)
Teaching Assignments: **(for each course write on a seperate line)**
Course No.: xxx \t Section No.: xxxx \t Course Name: xxxx \t Day and Time: dayOfWeek - timeOfweek
If no teaching assignments print: none
使用名为“teaches”的 ArrayList 变量,我可以从中获取所有信息。
我只是不明白我应该如何返回这种可能很长的字符串。 我应该使用某种字符串缓冲区吗?如何在每两个部分之间添加单独的行。
这是我的代码,为了清楚起见:
public String toString() {
String s ="";
int i=1;
if (this.teaches.isEmpty()){
return "none";
}
for(Section current: this.teaches){
s=s+"Course No"+i+" Section No:"+current.getSectionNo()+" Course Name:"+current.getRepresentedCourse().getCourseName()+" Day and Time"+current.getTimeOfDay();
}
return new String (this.getName()+" (Associatr Professor, "+this.department+" )"+s);
}
最佳答案
是的,请使用StringBuilder
:
public String toString()
{
StringBuilder builder = new StringBuilder();
if (!this.teaches.isEmpty())
{
for(Section current: this.teaches)
{
builder.append("["
.append("Course No ")
.append(i)
.append(" Section No: ")
.append(current.getSectionNo())
.append(" Course Name: ")
.append(current.getRepresentedCourse().getCourseName())
.append(" Day and Time ")
.append(current.getTimeOfDay())
.append("]");
}
}
return builder.toString();
}
或者,更好的是,有一个 Course
类而不是一堆原始字符串,只需打印出 List<Course>
,调用其 toString()
列表中每个条目的方法。
关于java - Java 中的字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5875099/