简体   繁体   English

ArrayList for循环仅适用于第一个元素

[英]ArrayList for-loop is only working for the first element

I'm working on a project in Javascript that requires me to write a class with a method that prints the information for a Tree object in a certain format. 我正在使用Javascript进行一个项目,该项目要求我编写一个类,该类使用一种方法以某种格式打印Tree对象的信息。 This is my toString method so far (the t.toString() inside the method is a reference to a different toString method in a different class). 到目前为止,这是我的toString方法(该方法内部的t.toString()是对不同类中不同toString方法的引用)。 It's supposed to display the information for one Tree object, then go to a new line and display the information for the next Tree object. 它应该显示一个Tree对象的信息,然后转到新行并显示下一个Tree对象的信息。

public String toString() 
    {
        for (Tree t : db) 
        {
            return t.toString() + "\n";
        }

        return null;
    }

I tested the method using this code. 我使用此代码测试了该方法。

 TreeDB trees = new TreeDB();

        Tree oak = new Tree("Oak", 24, 27);
        Tree maple = new Tree("Maple", 8, 38);
        Tree spruce = new Tree("Spruce", 11, 32);

        trees.add(oak);
        trees.add(maple);
        trees.add(spruce);

        System.out.println(trees.toString());

It prints the information for Oak, but not for Maple or Spruce. 它打印Oak的信息,而不打印Maple或Spruce的信息。 I'm assuming something is wrong with the header for my for-loop. 我假设for循环的标题出了点问题。 Can someone help me figure out how to make it print the information for all of the Tree objects? 有人可以帮助我弄清楚如何使其打印所有Tree对象的信息吗?

(a) Please recheck your loop. (a)请重新检查您的循环。

(b) Your question says you're working on a Javascript project yet the code you posted is in Java. (b)您的问题是您正在开发Javascript项目,但是发布的代码是Java。

You exit the function after reading the first element, returning its String representation. 在读取第一个元素并返回其String表示形式后,您可以退出该函数。 Use a StringBuffer to store all elements : 使用StringBuffer存储所有元素:

    public String toString() 
    {
        StringBuffer result = new StringBuffer();
        for (Tree t : db) 
        {
            result.append(t.toString()).append("\n");
        }

        return result.toString();
    }

In your for each loop you're returning the first value. for each循环中,您将返回第一个值。

Use StringBuilder (sb) to store (append) all the values and then return sb.toString() 使用StringBuilder(sb)存储(附加)所有值,然后return sb.toString()

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

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