Java / Android:ArrayIndexOutofBoundsException

时间:2012-05-18 01:37:13

标签: java android arrays sqlite

我有一张充满计算的表格。每行包含基于个人债务的数字。例如:

第1行:债务1(名称),7.9(APR),1000(余额),20(MinPayment);

第2行:债务2(名称),9.9(APR),2000(余额),40(MinPayment);

等。

此测试共有6行。我正在做几个带有几个数组的循环,我得到了上面的错误(标题中)。

  

05-17 18:31:47.548:E / AndroidRuntime(2019):引起:   java.lang.ArrayIndexOutOfBoundsException:length = 6;指数= 6

这是奇怪的,因为长度是6?

以下是整个方法:

 public int payoffDebt(Double totalDebt) {
    Cursor c = database.rawQuery("SELECT *  FROM debt;", null);
    int monthTotal = 0; 
    double interestFee = 0;
    double interestFeeTotal = 0;

    String indBal[] = new String[c.getCount()];
    String indPay[] = new String[c.getCount()];
    String indApr[]  = new String[c.getCount()];
    double totalBal[]  = new double[c.getCount()];
    double totalInterestFees[]  = new double[c.getCount()];
    int rowCounter[] = new int[c.getCount()];

    int j = 0; int k = 0;   
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        // get individual Bal, APR percent, Payment, store into three arrays;
        indBal[k++]  = c.getString(c.getColumnIndex("debt_total"));
        indPay[k++] = c.getString(c.getColumnIndex("payment"));
        indApr[k++] = c.getString(c.getColumnIndex("apr"));
        rowCounter[k++] = k;
    }
    c.close();

    while (totalDebt >= 0) {

        for (int i : rowCounter) {
            interestFee = (((Double.valueOf(indApr[i]) / 100) / 12) * Double
                    .valueOf(indBal[i]));
            totalDebt = totalDebt
                    - (Double.valueOf(indPay[i]) - interestFee);
            interestFeeTotal += interestFee; // sum of all Apr Fees CURRENT
                                                // month in while loop
        }

        totalBal[j++] = totalDebt; // record total debt for this after all
                                    // payments
        totalInterestFees[j++] = interestFeeTotal; // record total interest
                                                    // fees for this month
                                                      // from all debt

        // Increment month
        monthTotal += 1;

    }
    return monthTotal;

问题是第165行:

indApr[k++] = c.getString(c.getColumnIndex("apr"));

2 个答案:

答案 0 :(得分:4)

Java数组从0开始,而不是1.这意味着使用array[0]访问数组的第一个元素,使用array[1]访问第二个元素等。这样,访问最后一个元素数组,使用array[array.length - 1]。使用array[array.length]是一个超出范围的索引,因此是例外。

答案 1 :(得分:1)

其他人已经讨论过如何修复数组索引问题,但可能根本原因是你有五个独立的数组必须保持同步。如果您创建了一个新类来保存五项数据:

public class Data{
    String indBal;
    String indPay;
    String indApr;
    double totalBal;
    double totalInterestFees;
}

并且只有一个数据数组,那么循环索引应该更容易跟踪。