使用数组中的串联整数创建字符串时出现问题

Problem creating String using concatenated Integers from Arrays

这是一个重量加载程序,使用贪婪的方法来填充大篷车中的货车。 我正在尝试将数组中的 Integer 元素连接到必须遵循此模式的字符串输出中。

```
(wagon capacity) -> (weights of packages in wagon) = (total weight of the wagon)
100 –> (70, 25) = 95
200 -> (100, 90) = 190
140 –> (78, 60) = 138
600 –> (600) = 600
```

现在我的代码对我的容量和重量进行排序(降序),并将它们添加到一个 onBoard 变量中,当我尝试打印时,它正确显示了容量,但它没有连接我的重量,同时时间重用第一个权重。这是我的代码,任何反馈将不胜感激。

```
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    Integer[] cartCapacity = {100, 200, 140, 600};
    Integer[] cargoTons = {50, 60, 70, 100, 50, 41, 25, 78, 90, 41, 600};

    /*Desired output
     *(wagon capacity) -> (weights of packages in wagon) = (total weight of the wagon)
     * 100 –> (70, 25) = 95
     * 200 -> (100, 90) = 190
     * 140 –> (78, 60) = 138
     * 600 –> (600) = 600
     * 
     * Current output
     * 600->{600}
     * 200->{600}
     * 140->{600}
     * 100->{600}
     */

    //Sorting Carts
    Arrays.sort(cartCapacity, Collections.reverseOrder());
    //Sorting package tonnage
    Arrays.sort(cargoTons, Collections.reverseOrder());


    //After sorting carts
    System.out.println("The carts capacities are: ");
    for (int i = 0; i < cartCapacity.length; i++) {
        System.out.println(cartCapacity[i]);
    }


    System.out.println();


    //After sorting package tonnage
    System.out.println("The packages weights are: ");
    for (int i = 0, k = 0; i < cargoTons.length; i++) {
        System.out.println(cargoTons[i]);
    }


    int cartOnBoard = 0;
    int cartIdx = 0;
    String cartElements = "";
    while (cartIdx < cartCapacity.length) {
        for (int i = 0; i < cargoTons.length; i++) {
            if (cartOnBoard + cargoTons[i] <= cartCapacity[cartIdx]) {
                cartOnBoard += cargoTons[i];
                cartIdx++;
                cartElements += Integer.toString(cartOnBoard);
                System.out.println(Integer.toString(cartCapacity[i]) + "->{" + cartElements + "}");
            } 
            else
                System.out.println(Integer.toString(cartCapacity[i]) + "->{" + cartElements + "}");
        }
    }
    }
```

有多个问题,这里是带注释的固定循环:

int cartIdx = 0;
while (cartIdx < cartCapacity.length) {
    int cartOnBoard = 0; // this should be initialized for every cart
    String cartElements = ""; // this should be initialized for every cart
    for (int i = 0; i < cargoTons.length; i++) {
        if ((cartOnBoard + cargoTons[i]) <= cartCapacity[cartIdx] && cargoTons[i] > 0) {
            cartOnBoard += cargoTons[i];
            cartElements += Integer.toString(cargoTons[i]) + ",";
            cargoTons[i] = -1; // you need to mark used cargos
        }
    }
    System.out.println(Integer.toString(cartCapacity[cartIdx]) + "->{" + cartElements + "}"); // print one line per cart, not per every cargo
    cartIdx++;
}