2014-01-28 71 views
-1

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

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

}

+4

嗨。要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或者添加打印语句)来分析问题,追踪程序的进度,并将其与预期发生的情况进行比较。只要两者发生分歧,那么你就发现了你的问题。 (然后,如果有必要,你应该构造一个[最小测试用例](http://sscce.org)。) –

+8

'public void add(String item){ item = new String();'你确定你想要做到这一点? –

+1

您正在覆盖'add'中的'String'值。 –

回答

0

这里有多种问题。首先,我建议:

1)失去了 “大小” 的成员变量

2)替换为ArrayList<String> list成员变量 “字符串[]列表”

3)使用list.size()代替一个单独的“size”变量

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

5)通过调试器。如您所期望的那样,验证“列表”会按照您的预期添加。

FINALLY

6)通过调试用于 “的toString()” 步骤。确保“列表”具有您所期望的大小和内容。

'希望可以帮到...

相关问题