簡體   English   中英

數組索引越界 - Java 遞歸方法

[英]Array Index Out Of Bounds - Java Recursive Method

我正在用 3 種不同的方法編寫一個程序來練習遞歸。 我已經成功實施了三個中的一個,但我現在有點卡在第二個上。 此方法嘗試計算字符數組中“微笑”(:)) 的數量。 我以為我寫對了,但是當我測試它時,我不斷收到 ArrayIndexOutOfBoundsException,但我不知道為什么。 我的方法如下:

public static int countSmiles(char[] letters, int index) {

    int smileCounter = 0;

    //If the array is less than 2 in length it cannot include ":)".
    if(letters.length < 2) {
        return 0;
    }

    //If there is a smile increment the counter.
    else if(letters[index] == ':') {
        if(letters[index+1] == ')') {
            smileCounter++;
        }
    }

    //Increment the index
    index++;

    //Recursive assignment
    smileCounter = countSmiles(letters, index);

    //Return number of smiles
    return smileCounter;

}

我正在測試的方法如下:

public static void main(String[] args) {

    char[] JavaCharArray = {'r', 's', 't', 'u', ':', ')', 'v'};
    System.out.println(countSmiles(JavaCharArray, 0));
}

從我的代碼看來,我試圖訪問的索引 (0) 不是負數,也不是大於提供的數組。 我真的只是不明白。

在遞歸方法中,您需要一個停止條件。 嘗試:

...
if(letters.length < 2) {
    return 0;
}

if (index + 2 > letters.length) {
    return 0;
}
...

暫無
暫無

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

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