我如何改变这个java方法,使其不依赖于lotNumber-1
对象首先使用Java 使用BlueJ的实用介绍 工作丢了这本书,我不明白这个练习要求我做什么 练习是 练习4.51重写getLot,使其不依赖于在集合的索引(number–1)中存储有特定编号的批次。例如,如果批号2已删除,则批号3将从索引2移动到索引1,所有较高的批号也将移动一个索引位置。你可以假设批次总是根据其批号按递增顺序存储我如何改变这个java方法,使其不依赖于lotNumber-1,java,arrays,sorting,Java,Arrays,Sorting,对象首先使用Java 使用BlueJ的实用介绍 工作丢了这本书,我不明白这个练习要求我做什么 练习是 练习4.51重写getLot,使其不依赖于在集合的索引(number–1)中存储有特定编号的批次。例如,如果批号2已删除,则批号3将从索引2移动到索引1,所有较高的批号也将移动一个索引位置。你可以假设批次总是根据其批号按递增顺序存储 /** * Return the lot with the given number. Return null if a lot with
/**
* Return the lot with the given number. Return null if a lot with this
* number does not exist.
*
* @param lotNumber The number of the lot to return.
*/
public Lot getLot(int lotNumber) {
if ((lotNumber >= 1) && (lotNumber < nextLotNumber)) {
// The number seems to be reasonable.
Lot selectedLot = lots.get(lotNumber - 1);
// Include a confidence check to be sure we have the
// right lot.
if (selectedLot.getNumber() != lotNumber) {
System.out.println("Internal error: Lot number "
+ selectedLot.getNumber()
+ " was returned instead of "
+ lotNumber);
// Don't return an invalid lot.
selectedLot = null;
}
return selectedLot;
} else {
System.out.println("Lot number: " + lotNumber
+ " does not exist.");
return null;
}
}
/**
*返回带有给定编号的批次。如果大量使用此选项,则返回null
*数字不存在。
*
*@param lotNumber要返回的批次号。
*/
公共地块getLot(内部地块编号){
if((lotNumber>=1)和&(lotNumber
用pesudo代码向正确的方向提示就可以了。
我对这个练习要求我做什么感到困惑
我会坦率地告诉大家,这是一节课,老师只是在给我们一本书,几乎没有什么指导。所以我不是在找人帮我写作业,我只是想得到一些帮助。请不要因为我的请求而解雇我。这是一个询问编码问题的地方?不提前谢谢 在您提供的代码中,有一个很大的假设:假设批号
i
存储在i-1
位置的数组中。如果我们不这样假设呢?我们不知道loti
可能在数组中的什么位置,所以唯一的解决方案是遍历数组并查找lot numberi
,希望我们能找到它。给定方法的算法依赖于lotlotNumber
存储在索引lotNumber-1
中。它只是通过索引查找它,并验证它是否找到了正确的一个
练习就是放弃这个假设。批号和索引不再如此密切相关。所以你不能只计算索引,你必须搜索批次
最简单的方法是查看收藏中的每个批次,找到匹配的批次号后返回。为此,可以显式或隐式地使用迭代器(“foreach”)。如果您的课程还没有涉及迭代器,您还可以使用for
循环对集合的所有现有索引进行计数
但这项工作规定,这些地段仍按顺序存放。这允许你修改简单的方法,一旦你发现比你要寻找的数字高很多,就放弃
最佳方法是使用排序列表的搜索算法,例如