java - 删除到期日期在给定日期之后的所有产品
问题描述
我有一个Date
类,它具有 _day、_month 和 _year 属性。我还有一个FoodItem
类,它的一个属性是项目的到期日期。(来自类型Date
)
现在,我正在创建一种方法,以从FoodItem
named数组中删除_stock
其到期日期在作为参数传递的 Date 之后的所有项目。
这是一项任务,因此我可能不会使用任何高级 Java 对象,例如 ArrayLists。
我可以使用的两种方法,位于类 Date 是before
和after
:
public boolean before(Date other) {
if (_year < other.getYear())
return true;
if (_month < other.getMonth() && _year == other.getYear())
return true;
if (_day < other.getDay() && _month == other.getMonth() && _year == other.getYear())
return true;
return false;
}
public boolean after(Date other) {
return other.before(this);
}
我尝试了以下方法:
public void removeAfterDate(Date d)
{
for(int i = 0; i <_noOfFoodItems; i++)
/*if item's expiry date is after the given date,
it will be deleted*/
if (_stock[i].getExpiryDate().before(d) /*also tried _stock[i].getExpiryDate().after(d), d.before(_stock[i].getExpiryDate()) and d.after(_stock[i].getExpiryDate())*/)
fillHoles(i);
}
private void fillHoles(int index)
{
//since the function deletes an item, the _noOfFoodItems counter should go down by 1
_noOfFoodItems--;
/*this will place each item, starting from the given index,
* one location in the array before where it currently is.
* this action will override the item that need to be deleted, while
* filling the "holes" created in the array becuse of the deleted item*/
for (int i = index; i < _noOfFoodItems; i++)
{
_stock[i] = _stock[i + 1];
_stock[i + 1] = null;
}
}
但是当运行以下测试器时:
new Test("removeAfterDate()", () -> {
Date date1 = new Date(1, 1, 2000);
Date date2 = new Date(1, 2, 2000);
Date date3 = new Date(1, 3, 2000);
Date date4 = new Date(1, 4, 2000);
FoodItem fi1 = new FoodItem("Name1", 1001, 1, date1,/*expiary date:*/ date2, 1, 10, 5);
//only this one should stay
FoodItem fi2_fresh = new FoodItem("Name2", 1002, 1, date1, /*expiary date:*/ date4, 5, 10, 5);
FoodItem fi3 = new FoodItem("Name3", 1003, 1, date1,/*expiary date:*/ date2, 1, 10, 5);
FoodItem fi4 = new FoodItem("Name4", 1004, 1, date1,/*expiary date:*/ date2, 1, 10, 5);
//this is the class removeAfterDate is located in
Stock actual = new Stock();
// this just add the items to the _stock array
actual.addItem(fi1);
actual.addItem(fi2_fresh);
actual.addItem(fi3);
actual.addItem(fi4);
actual.removeAfterDate(date3);
//line 145
assertEquals(actual, new FoodItem[]{fi2_fresh});
//line 147
assertEquals(actual.getNumOfItems(), 1);
})
我得到错误:
removeAfterDate(): 2 errors
At line 145: Expected:
[FoodItem: Name2 CatalogueNumber: 1002 ProductionDate: 01/01/2000 ExpiryDate: 01/04/2000 Quantity: 1
]
But got:
[FoodItem: Name2 CatalogueNumber: 1002 ProductionDate: 01/01/2000 ExpiryDate: 01/04/2000 Quantity: 1
FoodItem: Name4 CatalogueNumber: 1004 ProductionDate: 01/01/2000 ExpiryDate: 01/02/2000 Quantity: 1
]
At line 147: Expected 1 but got 2
我做错了什么?