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/