简体   繁体   English

如何格式化方法中的数组以在没有括号的单独行上返回

[英]How to format an array in a method to return on separate lines without brackets

I'm working on a toString method that takes in a name of a Array and returns the name and the "tasks" stored within the array. 我正在研究一个toString方法,它接受一个数组的名称并返回存储在数组中的名称和“任务”。 However, I'm unsure of how to format the array within the method in order to get it to print each index of the array on separate lines. 但是,我不确定如何在方法中格式化数组,以使其在单独的行上打印数组的每个索引。

What I have: 我有的:

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;
    }

What it results: 结果如何:

-------------
To Do List
-------------
[[X]Finish studying, 0, [ ]Last minute cramming, 20, [ ]Finish studying, 0, [ ]Finish studying, 0]

What it's supposed to look like: 应该是什么样子:

-------------
My ToDo List
-------------
[X] Finish studying, 0

[ ] Last minute cramming, 20

etc......

As @Dave Newton already mentioned, you will have to iterate through your tasks . 正如@Dave Newton已经提到的,你将不得不迭代你的tasks

Possible Solution : 可能解决方案

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM