這種方法拋出IndexOutOfBoundsException,我不明白爲什麼,因爲我已經防範了它。Java LinkedList中的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 at java.util.LinkedList.checkElementIndex(Unknown Source) at java.util.LinkedList.get(Unknown Source) at NextFit.next(NextFit.java:26) at Main.main(Main.java :58)
請提供完整的堆棧跟蹤。這是一個好習慣,通常會給你更好的答案。另外,如果可能的話 - 嘗試刪除對於您遇到的特定問題不需要的部分代碼 – amit
難道Tracking.getLast(col)返回庫存對象中不存在的索引嗎? – erikxiv
或者'col'在'tracking'中可能不存在,並且這會產生'-1',這會稍後導致您得到超出界限的異常。 – amit