簡體   English   中英

如何將第n個元素從char數組添加到arraylist?

[英]how to add nth element from char array to arraylist?

只是嘗試將char數組中的第n個元素添加到Array列表中。 但是,當我嘗試運行以下方法時,將收到ArrayIndexOutOfBoundsException。 我猜是因為數組到達末尾時我的x [i + 2]不起作用?

這是我的方法的代碼:

public void Encode (char[] x){
    for(int i = 3; i < x.length; i++) {

        mid.add(x[i+1]);
        bottom.add(x[i+2]);
        top.add(x[i]);
        top.removeAll(mid);
        top.removeAll(bottom);
    }
} 

 public ArrayList getTop(){
    return top;
}

public ArrayList getMid() {
    return mid;
}

public ArrayList getBottom() {
    return bottom;
}

}

錯誤在於數組索引中,要使用x[i+2]您需要將i限制為x.length-2 那是

for(int i = 3; i < x.length - 2; i++) {

當i = x.length-2時,+ 2是x.length(且超出范圍)。

mid.add(x[i+1]); is  throwing exception.

數組的大小必須始終比從數組中提取的索引大index + 1。

您應該使用類似

public void Encode (char[] x){
        for(int i = 3; i < x.length; i++) {


            int size=x.length-1;


            if (size>(i+1)) {
                 mid.add(x[i+1]);
            }

            if (size>(i+2)) {
                 bottom.add(x[i+2]);
            }
            if (size>i) {
                 top.add(x[i]);
            }


            top.removeAll(mid);
            top.removeAll(bottom);
        }
    }

由於x[i+2]引發ArrayIndexOutOfBoundsException ,因為i+2大於x.length

您可以在使用每次索引之前檢查索引是否有效。

出於好奇,要編碼的功能是什么?

暫無
暫無

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

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