簡體   English   中英

為什么我得到這個錯誤數組索引越界

[英]Why am I getting this error array index out of bounds

到目前為止,這是我的課程的代碼,如果沒有 (int) 解析,它將無法編譯而不會因為草率轉換 double 到 int 而出現錯誤

使用此當前代碼,它會編譯但不會運行而不會在monthlyFee 方法中出現異常錯誤

public class Bank {


    // instance variables=========================================
    // setup new array of BankAccount objects and internal null constructor
    BankAccount [] custAcct = new BankAccount[10];

    // data above here
    //===========================================================
    // methods down below

    // display methods=======================================

    public void printAccounts(){
        for(int i=0; i<custAcct.length; i++) {
            if (custAcct[i]!=null){
                System.out.println(custAcct[i]);
            }
        }   //end loop

    } // end method

    // utility methods=============================

    public void addAccount(BankAccount acct) {
        for(int i=0; i<custAcct.length; i++) {
            if (custAcct[i]==null){
                custAcct[i] = acct;
                break;
            }
        }   // end loop

    } // end method

    public BankAccount getAccount(int acc) {
        return custAcct[acc];
    } // end method

    public void monthlyFee (double acctVal){
        for(int i=0; i<custAcct.length-1; i++) {
            if (custAcct[i]!=null){
                custAcct[i] = custAcct[(int)acctVal];
                break;
            }
        }   // end loop

    } // end method

您的monthlyFee方法將在這一行拋出一個IndexOutOfBoundsException

custAcct[i] = custAcct[(int)acctVal];

如果acctVal比的長度較高custAcct (在這種情況下10)或大於0從您發布到你的問題的評論,我看你調用低monthlyFee與-2.95,這是你的源IndexOutOfBoundsException

您的addAccount方法也可能包含一個設計缺陷:根據它當前的編碼方式,它使用作為參數傳遞的BankAccount填充custAcct數組中的所有空白點。 如果您只想將帳戶添加到第一個空頭寸,請使用以下命令:

public void addAccount(BackAccount acct) {
    for(int i = 0; i < custAcct.length; i++) {
        if(custAcct[i] == null) {
            custAcct[i] = acct;
            return;
        }
    }
}

我認為這應該來自這里(也許發送堆棧跟蹤片段會有所幫助)

            custAcct[i] = custAcct[(int)acctVal];

為 acctVal 傳遞的值是什么,如果該值小於 0 或大於等於 custAcct.length,則可能存在 Array 越界異常。 另一個問題可能是 custAcct[i] 未初始化,並且可能存在空指針異常。 如果您提供堆棧跟蹤,可以更好地說明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM