1
        static final int[] HotDogdb = {30, 45, 44, 37,51};
    static final int[] ToastedChickendb = {25, 30, 45, 15,33};
    static final int[] ToastedSteakdb = {10, 15, 12, 16,17};
    static final int[] ToastedEggTdb = {14, 12, 17, 20,16};
    static final int[] ToastedSteakEdb ={5, 8, 3, 8,6};
    static final int[] ChickenRolldb = {27, 28, 23,20,21};
    static final int[] SteakRolldb = {19, 22, 23, 21,18};
    static final int[] EggTomatodb = {15, 16,10, 12,11};
    static final int[] CheeseTomatodb = {18, 19, 22, 21,20};
    static final int[] SteakEggdb = {10, 16, 13, 17,15};
    static final int[] tCheeseTomatodb = {23, 30, 27, 40,37};
    static final int[][] sales = new int[][] { HotDogdb, ToastedChickendb, ToastedSteakdb, ToastedEggTdb, ToastedSteakEdb,ChickenRolldb,SteakRolldb,EggTomatodb,CheeseTomatodb, SteakEggdb, tCheeseTomatodb };

所以基本上通过我到目前为止找到的 index @ 0 的总和

int total8 = 0;
int i;


for (i=0; i <= 11; i++){
total8 = total8 +  MyConstants.sales[i][0];}
                                jTextArea6.setText(""+total8);
4

1 回答 1

2

而不是i <= 11,使用i < 11

for (i=0; i < 11; i++) {

否则,您将得到一个ArrayOutOfBoundsException, since sales.lengthis 11,并且您正在使用i <= 11,因此,您的最后一次迭代将尝试访问sales[11]不存在的(注意 Java 中的数组是0-indexed)。

另一种选择是使用i < sales.length. 这样,如果您向数组添加更多元素,则无需更改for-loop 的代码:

for (i=0; i < sales.length; i++) {
于 2012-09-09T11:39:52.970 回答