如何打印数组元素的索引位置

时间:2016-02-18 07:14:25

标签: java

假设我有一个31元素的数组,每个元素包含例如1月份的费用;假设我在某些日子里没有任何费用。 如何打印元素以及该元素的索引或下标。

  例如,第25天有100美元      第31天有200美元      但它打印得像这样      第1天$ 100
     第2天$ 200

for(daysCounter=0; daysCounter<31; daysCounter++) { 
    if(januaryExpenses[daysCounter]>0) {    
        System.out.println(" expense for day " + (daysCounter +1) + " is $" + januaryExpenses[daysCounter]);
        monthTotal=monthTotal+januaryExpenses[daysCounter];

    } else {
        System.out.print("");
    }       
}
System.out.println("Your January expenses are: $" +monthTotal);

2 个答案:

答案 0 :(得分:0)

问题是您插入到$100索引中的数组0而不是24索引中,并且$200索引中的1不插入{{1}你拥有的索引:

30

您需要在范围 day 1 $100 day 2 $200 索引中插入值为0的数据,并在0-23索引插入24中插入,依此类推$100

答案 1 :(得分:0)

好像你只为持有费用的那一天增值。即

int[] januaryExpenses = {100,200};

而不是您的数组januaryExpenses必须包含31个元素。一世。即

int[] januaryExpenses = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,0,0,0,200};

那么你的代码就可以了

int[] januaryExpenses = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,0,0,0,200};
for(int daysCounter=0; daysCounter<31; daysCounter++) { 
    if(januaryExpenses[daysCounter]>0) {    
        System.out.println(" expense for day " + (daysCounter +1) + " is $" + januaryExpenses[daysCounter]);
        monthTotal=monthTotal+januaryExpenses[daysCounter];

    } else {
        System.out.print("");
    }       
}
System.out.println("Your January expenses are: $" +monthTotal);