java - 为什么下面的代码只显示循环最后一圈的数组值?

标签 java arrays

public static void displaySummary(int totalShipment,
                                  String[] nameOfBus,
                                  int[][] storageBox)
{
    int counter;

    //Display the Summary Report              
    System.out.println("\nSummary\n- - - - - - - - - - - -");
    for(counter = 0; counter < totalShipment; ++counter)
    {
        System.out.println("Shipment #" + (counter + 1)+  " - " + nameOfBus[counter]);
        System.out.print("\nXL - " + storageBox[0][counter] + ",");
        System.out.print("L - " + storageBox[1][counter] + ",");
        System.out.print("M - " + storageBox[2][counter] + ",");
        System.out.print("S - " + storageBox[3][counter]+"\n");
    }

    System.out.println("\nTotal Number of containers required for these shipments:\n");
    System.out.println("XL - " + totalXL);
    System.out.println("L - " + totalL);
    System.out.println("M - " + totalM);
    System.out.println("S - " + totalS);        
}

当我从 main 调用 displaySummary 时,无论发货数量是多少,都只会打印循环最后一圈的值...如果只有一次发货,则会打印这些值。如果两次发货,则打印第二圈循环的值,但第一圈不会打印......

最佳答案

这是一个典型的初学者错误。

如果您通过以下方式添加多个项目:

int n = 0;
int[] box = new int[4];

box[0] = ...; box[1] = ...; ...
storageBox[n] = box;
++n;

box[0] = ...; box[1] = ...; ...
storageBox[n] = box;
++n;

box[0] = ...; box[1] = ...; ...
storageBox[n] = box;
++n;

错误是,您刚刚创建的同一个对象 new int[] 被放置在 storageBox[0]、[1] 和 [2]。您多次覆盖 sama 数组 box[0..4] 直至最后一个值。

所以storageBox[0] == storageBox[2]并且它们的数组值是相同的。

对于每个 storageBox 项,您必须添加一个 new int[4]

关于java - 为什么下面的代码只显示循环最后一圈的数组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38418021/

相关文章:

java - 如何从列表转换为数组?安卓

java - Windows 和 Unix 之间的 ZoneDateTime 精度差异

java - Java中的音频输入捕获——字节数组

javascript - JavaScript 中数组的求和值

python - 根据复杂条件选择和重新分配数组中元素的最快方法

Javascript 无法正确排序包含两个数组值的数组

JavaScript 与其他数组相比替换数组的匹配成员

java - 什么相当于 Android 中的 C# AsyncTask?以及如何强制停止它?

Java 对其他类的独占方法

java - 如果实体本身的实体监听方法和生命周期回调重复怎么办?