【问题标题】:Why isn't my toString method working in Java?为什么我的 toString 方法在 Java 中不起作用?
【发布时间】:2014-01-28 00:07:01
【问题描述】:

我正在编写一个新闻提要程序,我正在尝试检查项目是否正确地添加到列表数组中。在我的测试工具中,我尝试在添加一个组合项后打印数组的内容,但是当我运行程序时,什么都没有显示。我的 toString 方法(或其他)有问题吗?谢谢你的帮助。

public class Feed {

private final int DEFAULT_MAX_ITEMS = 10;   // default size of array

/* Attribute declarations */
private String name;        // the name of the feed
private String[] list;      // the array of items
private int size;           // the amount of items in the feed

/**
 * Constructor
 */
public Feed(String name){
    list = new String[DEFAULT_MAX_ITEMS];
    size = 0;
}

/**
 * add method adds an item to the list
 * @param item
 */
public void add(String item){
    item = new String();

    // add it to the array of items
            // if array is not big enough, double its capacity automatically
            if (size == list.length)
                expandCapacity();

    // add reference to item at first free spot in array
            list[size] = item;
            size++; 
    }

/**
 * expandCapacity method is a helper method
 * that creates a new array to store items with twice the capacity
 * of the existing one
 */
private void expandCapacity(){
    String[] largerList = new String[list.length * 2];
    for (int i = 0; i < list.length; i++)
        largerList[i] = list[i];

    list = largerList;
}


/**
 * toString method returns a string representation of all items in the list
 * @return 
 */
public String toString(){
    String s = "";
    for (int i = 0; i < size; i++){
        s = s + list[i].toString()+ "\n";
    }
    return s;
}

/**
 * test harness
 */

public static void main(String args[]) {
    Feed testFeed = new Feed("test");
    testFeed.add("blah blah blah");
    System.out.println(testFeed.toString());
}

}

【问题讨论】:

  • 嗨。要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或添加打印语句)来隔离问题,方法是跟踪程序的进度,并将其与您期望发生的情况进行比较。一旦两者发生分歧,你就发现了你的问题。 (然后如果有必要,你应该构造一个minimal test-case。)
  • public void add(String item){ item = new String(); 你确定要这样做吗?
  • 您正在覆盖add 中的String 值。
  • 你一定要使用String[]吗?如果您可以使用ArrayList&lt;String&gt;,则无需担心在达到最大大小时扩展数组。
  • 我认为我的问题在于我的 add 方法,正如你们中的一些人所说的(仅供参考,我必须使用 String[])。如何将作为参数的字符串项添加到数组中?这是代码的关键部分:public void add(String item){ item = new String(); 我是否必须使用this 也许?

标签: java tostring


【解决方案1】:

这里有多个问题。对于初学者,我建议:

1) 丢失“size”成员变量

2) 用ArrayList&lt;String&gt; list 替换成员变量“String[] list”

3) 使用list.size() 而不是单独的“大小”变量

4) 你也可以丢失(或简化)你的“add()”方法。只需改用list.add()

5) 单步调试调试器。验证“列表”是否按预期添加。

终于

6) 单步调试“toString()”。确保“列表”具有您期望的大小和内容。

'希望对您有所帮助...

【讨论】:

    猜你喜欢
    • 2011-02-25
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    相关资源
    最近更新 更多