0
我有一種方法可以將一個對象添加到數組中,但它會根據順序添加它。所以我們可以說我有一個有蘋果和可樂的數組。如果我想添加一個香蕉,它會在這兩個對象之間。但是當我運行我的jUnit測試時,我不斷收到錯誤。下面是代碼:根據訂單在數組中添加東西
/**
* Adds an item to the list. This method assumes that the list is already
* sorted in alphabetical order based on the names of the items in the list.
*
* The new item will be inserted into the list in the appropriate place so
* that the list will remain alphabetized by names.
*
* In order to accomodate the new item, the internal array must be re-sized
* so that it is one unit larger than it was before the call to this method.
*
* @param itemToAdd refers to a Listable item to be added to this list
*/
public void add(Listable itemToAdd) {
int i;
Listable[] newItems = new Listable[items.length+1];
for(i=0; i<items.length;i++){
if(items[i].getName().compareTo(itemToAdd.getName()) < 0){
newItems[i] = items[i];
} else{
break;
}
}
int str=i;
for(i=str+1;i<items.length;i++){
newItems[i+1] = items[i];
}
newItems[str] = itemToAdd;
}
我不斷收到指出該測試預計< 14錯誤>但得到< 0>所以現在我認爲這意味着其我的構造函數這就是問題:
/**
* This constructor creates an empty list by creating an internal array
* of size 0. (Note that this is NOT the same thing as setting the internal
* instance variable to null.)
*/
public SortedListOfImmutables() {
int i = 0;
items = new Listable[0];
//orders the list
for(i=0;i<items.length;i++){
if(Food.FOOD_OBJECTS[i].getName().compareTo(Food.FOOD_OBJECTS[i+1].getName()) < 0){
items[i] = Food.FOOD_OBJECTS[i];
}else{
items[i+1] = Food.FOOD_OBJECTS[i];
}
}
}
你也可以發表您的junit在這裏?另外,我對「items」是一個大小爲零的空數組感興趣,我們在循環中添加了一些東西。我錯過了什麼嗎? – Wizard
爲什麼測試期望「14」?哪個測試,它有什麼作用?你很難幫助你。 – Meier