这个方法抛出一个IndexOutOfBoundsException,我不明白为什么我已经提防它了。
private static boolean firstLoop(int custNo, LinkedList<Pipe> stock, LinkedList<Customer> custs, Random generator, String colour, int col, Tracking tracking) {
if ((stock.get(tracking.getLast(col)) != null) && (stock.get(tracking.getLast(col)).getLength() >= custs.get(custNo).getLength())) {
stock.get(tracking.getLast(col)).length = Cut.cut(stock.get(tracking.getLast(col)).getLength(), custs.get(custNo).getLength(), colour);
if (stock.get(tracking.getLast(col)).length < 5) {
stock.remove(tracking.getLast(col)); //**CAUSES EXCEPTION**
tracking.add();// recycle
}
return true;
} else {
for (int j = tracking.getLast(col) + 1; j < stock.size(); j++) {
if ((stock.get(j).getLength() >= custs.get(custNo).getLength())) {
// pipe is long enough, cut away the desired length
stock.get(j).setLength(Cut.cut(stock.get(j).getLength(), custs.get(custNo).getLength(), colour));
tracking.setLast(col, j);
return true;
}
}
// no suitable pipes available, order new one of correct colour with
// random length 100-200 then cut from it, add to arraylist
Pipe temp2 = new Pipe(col, generator.nextInt(101) + 100);
temp2.setLength(Cut.cut(temp2.length, custs.get(custNo).length, colour));
stock.add(temp2);
tracking.setLast(col, stock.size() - 1);
return false;
}
}
我发现标记的行是导致异常的行(程序在被注释掉时运行完美)。但是,我很困惑,因为 tracking.getLast(col) 在它上面的行中完美地工作,并且 remove 函数不在迭代器或循环内。这是跟踪类:
public class Tracking {
static int lastR=0;
static int lastG=0;
static int lastY=0;
public void setLast(int col, int last){
if(col==0){
lastR=last;
}else if(col==1){
lastG=last;
}else if(col==2){
lastY=last;
}else{
System.out.println("Colour does not exist");
}
}
public static int getLast(int col){
if(col==0){
System.out.println(lastR+" red");
return lastR;
}else if(col==1){
System.out.println(lastG+" green");
return lastG;
}else{
System.out.println(lastY+" yellow");
return lastY;
}
}
这是使用引发错误的方法:
if ((yellowStock.get(Tracking.getLast(2)) != null) && (yellowStock.get(Tracking.getLast(2)).getLength() >= custs.get(i).getLength())) {
firstLoop(i, yellowStock, custs, generator, "yellow", 2, recycle);
}
线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:3,大小:3 在 java.util.LinkedList.checkElementIndex(Unknown Source) at java.util.LinkedList.get(Unknown Source) at NextFit.next(NextFit. java:26) 在 Main.main(Main.java:58)