-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());
}
}
嗨。要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或者添加打印语句)来分析问题,追踪程序的进度,并将其与预期发生的情况进行比较。只要两者发生分歧,那么你就发现了你的问题。 (然后,如果有必要,你应该构造一个[最小测试用例](http://sscce.org)。) –
'public void add(String item){ item = new String();'你确定你想要做到这一点? –
您正在覆盖'add'中的'String'值。 –