簡體   English   中英

如何檢查數組中的下一個元素是否為空-Java

[英]How to check If the next element in an array is null - Java

我正在創建一個很大的多類程序,只需要找出數組中的下一個元素是否存在於我的一個方法中即可。 (即,如果i是最后一個元素)。

我的代碼:

if (eMessageArray[i + 1] != null) {
    temp = stringShuffle(eMessageArray[i], eMessageArray[i + 1]);
    eMessageArray[i] = temp;
} else if (eMessageArray[i + 1] == null) {
    temp = stringShuffle(eMessageArray[i], "NULL");
    eMessageArray[i] = temp;
}

問題在於,當i指向數組的最后一個元素時,則沒有元素i+1 ,因為數組不夠長。 解決方案是停止在倒數第二個索引處使用i進行迭代,以使i+1始終是有效索引。 這是通過...length - 1 ,如下所示:

for (int i = 0; i < eMessageArray.length - 1; i++) { // important: - 1 to omit last index for i
    if (eMessageArray[i+1]!=null){
        temp = stringShuffle(eMessageArray[i], eMessageArray[i+1]);
    } else {
        temp=stringShuffle(eMessageArray[i], "NULL");
    }
    eMessageArray[i]=temp;
}

通常,當嘗試越界訪問數組索引時,可能會出現一些垃圾值,這些值雖然不是null卻無意義被訪問。 如果要使用數組,則需要定義數組的bounds &&在迭代內部為邊界范圍提供該檢查。

暫無
暫無

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

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