このメソッドは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);
}
スレッド"main"の例外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)Main.main(Main.java:58)で