LinkedList给我错误的输出?

时间:2017-05-25 10:52:28

标签: java linked-list output tostring

我在我的LinkedList上挣扎。输出错误。 我明白了:`

[January 2016, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]

我想要的是:

January 2016 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31`

这就是我的声明和初始化我需要的变量;

private final String[] monthname = {null, "January", "February", "March", "April", "May", "June", "July",
            "August", "September", "October", "November", "December"};

    private LinkedList<LinkedList<String>> planlist = new LinkedList<>();
    private int year = 2017; // Default year

这是构建月纸的方法。在这个方法中,我添加到LinkedList值并将其作为类型返回给另一个LinkedList。

public LinkedList<String> buildMonth(int month) {
    StringBuilder stringBuilder = new StringBuilder();
    LinkedList<String> monthList= new LinkedList<>();
    String header= this.monthname[month] + " " + this.year;
    monatListe.add(header);

    for (int i = 1; i <= 31; i++) {
        String converterInt = String.valueOf(i);
        monthList.add(converterInt.toString());

    }
    return monthList;
}

最后,我想告诉你如何输出我的LinkedList。我尝试使用迭代器,但它不起作用所以我决定这样做。

    public String getYearplan(int from, int until) {
        if (von <= bis) {
            for (int i = von; i <= bis; i++) {
                this.planlist.add(buildMonth(i));
                System.out.println(buildMonth(i));
            }
        }
return null;
}

我希望你能帮助我弄清楚,但没有任何效果。我尝试使用toString()而不使用toString,但我不知道。

最好的问候

Michael Dev

3 个答案:

答案 0 :(得分:1)

你正在做

System.out.println(buildMonth(i));

buildMonth()返回LinkedList<String>println需要打印一个字符串,因此它会调用LinkedList的{​​{1}}。您看到的输出是toString()生成的内容,toString()的程序员认为对其他尝试使用LinkedList的程序员最有用的内容。

由于您不喜欢LinkedList开发人员为您提供的内容,您只需要自己动手并按照您希望的方式对输出进行编程。这样的事情,也许是:

LinkedList

答案 1 :(得分:0)

所以你只想要一个字符串,其值由空格分隔,然后执行以下操作:

String.join(" ", planlist);

答案 2 :(得分:0)

也许,这应该是......?

public String getYearplan(int from, int until) {
    if (from <= until) {
        for (int i = from; i <= until; i++) {
            List list = buildMonth(i);
            this.planlist.add(list);
            System.out.println(list);
        }
    }
    return null;
}