我正在研究一个toString方法,该方法接受一个Array的名称并返回名称和存储在该数组中的“任务”。但是,我不确定如何在方法中格式化数组,以使其在单独的行上打印数组的每个索引。
我所拥有的:
import java.util.ArrayList;
import java.util.Collections;
public class ToDoList implements ToDoListInterface {
private String name;
private ArrayList<Task> tasks;
public ToDoList (String name)
{
this.name = name;
tasks = new ArrayList<Task>();
}
public String toString(String name)
{
return "-------------" + "\n" + name + "\n" + "-------------" + "\n" + tasks;
}
结果如何:
-------------
To Do List
-------------
[[X]Finish studying, 0, [ ]Last minute cramming, 20, [ ]Finish studying, 0, [ ]Finish studying, 0]
应该是什么样子
-------------
My ToDo List
-------------
[X] Finish studying, 0
[ ] Last minute cramming, 20
etc......
答案 0 :(得分:0)
正如@Dave Newton已经提到的那样,您将不得不遍历tasks
。
可能的解决方案:
public String toString(String name) {
String ret = "-------------" + "\n" + name + "\n" + "-------------" + "\n";
for(Task t: tasks) {
ret += "[" + (t.isFinished() == true ? "X" + : " ") + "] " + t.getTitle() + ", " + task.getDuration() + "\n";
}
return ret;
}