我正在尝试进行首次安装的垃圾箱包装。这是我编写的代码,每行都有解释作为注释:
private void runFirstFit(ActionEvent event) {
// The counters
int i;
int j = 0;
// The boolean
packingComplete = false;
// Declare an arrayList from the numbers the user has entered
ArrayList<Integer> numbers = new ArrayList(6);
// Add numbers into the array from input (using a loop)
for (i = 0; i < 6; i++) {
numbers.add(parseInt(getNumber(i)));
}
// - Main packing algorithm starts here -
// Iterate through arraylist and get next number
Iterator<Integer> iterator = numbers.iterator();
// While there are still numbers left, try and add to bins
while (iterator.hasNext()) {
// Number(s) still exist in the list
// Check if number can fit inside bin
System.out.println("Number currently in queue: " + iterator.next());
if (canNumberFitInsideBin(j, iterator.next())) {
// Put number inside bin
bin[j] += String.valueOf(iterator.next()) + ", ";
System.out.println("Number added to bin " + j);
} else {
// Bin is full, move to the next bin (increment counter)
j++;
// Put number inside that bin
bin[j] += String.valueOf(iterator.next()) + ", ";
System.out.println("Counter incremented");
}
}
// Update all labels
updateAllBinLabels();
}
基本上,getNumber(i)
部分是一个返回数字的函数。我正在使用循环将实际数字(更具体地说,其中 6 个)添加到名为"数字"的 ArrayList 中。
我尝试在每个阶段打印出数字,看看它正在处理哪个数字 - 但似乎它只是无缘无故地随机跳过了一些数字。例如,对于 ArrayList 输入 1,2,3,4,5,6
它添加到bin[0]
的第一个数字是3
(应该是1
),然后它还将6
添加到bin[0]
并忽略所有其他数字并转到下一个 bin 数组。
谁能发现我做错了什么?
谢谢
最明显的问题是 iterator.next() 每次进入循环只应该调用一次。 每次调用它时,您都在列表中前进。 您需要调用它一次,并将其保存在循环顶部的临时变量中。
此外,您可能应该检查该数字是否可以放入其他箱的下一个箱中,除非您知道没有一个值比您的箱大小大。