我試圖找到可以放置在NxN二維數組中的任何位置的特定元素(數字0)的鄰居。如果0位於中心位置,則這不成問題,但如果它位於頂部/底部的行上,則不會有高於/低於其的值,並且與最左側/右側相同角落案件。應該指出,我只需要檢查直接水平/垂直於它的值,而不是對角線。是否有可以調用的特定方法來確定特定索引是否存在?試圖找出如何檢查一個潛在的數組元素是否超出範圍
0
A
回答
2
您可以從數組長度中獲取該信息。
給定一個2維陣列array[m][n]
,你考慮第一維以表示行,而第二維以表示列:
array[0][whatever] // top row
array[m-1][whatever] // bottom row
array[whatever][0] // left-most column
array[whatever][n-1] // right-most column
應用該(格式化爲可讀性):
Object current = array[i][j];
Object left = j > 0 ? array[i][j-1] : null;
Object right = j < (n - 1) ? array[i][j+1] : null;
Object top = i > 0 ? array[i-1][j] : null;
Object bottom = i < (m - 1) ? array[i+1][j] : null;
無論如何:不要通過捕獲ArrayIndexOutOfBoundsException
來解決此問題。捕獲可以100%避免的運行時異常被認爲是不好的形式。
0
如採取
[3][3] array
和i and j
是行和列的索引
只是檢查
//horizontal
if(i - 1 >= N){ //N being 3
//do check for
}
if(i + 1 <= N){ // N being 3
//do check
}
//vertical
if(j - 1 >= N){ //N being 3
//do check for
}
if(j + 1 <= N){ // N being 3
//do check
}
雖然ID喜歡剛好圍繞我的整個操作(檢查鄰居-1和+ 1水平和垂直)與一個嘗試捕獲
try{
//your checks for correct and incorrect indexes doesnt matter if it goes beyond.
}catch(ArrayIndexOutOfBoundsException e){
// handle here let all other exceptions break your program
}
0
這很容易使用異常處理方法。
somefunction(int arr[10][10], int num){
int i, j;
for(i=0; i<10; i++){
for(j=0; j<10; j++){
if(arr[i][j]==num)
break;
}
}
//i is rows and j is columns
try{
for(int k=-1 ; k<=1; k++){
for(int l=-1 ; l<=1; l++){
System.out.println(arr[i+k][j+l]);
}
}
}
catch (ArrayIndexOutOfBoundsException e){
}
}
相關問題
- 1. 如何檢查數組索引是否超出範圍SWIFT
- 2. 如何檢查二維數組是否超出範圍?
- 3. 如何檢查數組索引是否超出範圍?
- 4. 多維數組超出範圍檢查
- 5. 我試圖檢查索引是否超出範圍,但我使用的代碼是索引超出範圍?
- 6. 試圖找出如何檢查值是否在數組
- 7. 檢查數組[鍵]是否設置?拋出:索引超出範圍
- 8. 如何使一個元素超出其父範圍?
- 9. 如何測試無符號__int64數字是否超出範圍
- 10. 當我將一個元素插入數組時,數組索引超出範圍
- 11. Unity3D:數組超出範圍
- 12. 數組超出範圍
- 13. 數組查詢,索引超出範圍
- 14. 如何檢查一個數組的元素是否在另一個數組中?
- 15. 刪除超出範圍的上層數組元素php
- 16. 檢查超出C的範圍
- 17. 如何檢測ScrollViewer是否超出其可用範圍
- 18. C#檢查對象是否超出範圍(GUI)
- 19. Array to Excel範圍只給出數組的第一個元素
- 20. 下標超出範圍,Excel VBA,試圖在循環內創建一個數組
- 21. 元組索引超出範圍Tkinter
- 22. numpy.savetxt「元組索引超出範圍」?
- 23. Python - 「元組索引超出範圍」
- 24. IndexError:元組索引超出範圍
- 25. numpy.savetxt IndexError:元組索引超出範圍
- 26. python:IndexError:元組索引超出範圍
- 27. 如何檢查數字是否在一個範圍內?
- 28. 測試超出範圍
- 29. 如何檢查一個角色是否在一個範圍內
- 30. 如何找出一個HTML元素是否在另一個HTML元素之後?
正確,但如果[0] [whatever]導致一個不存在的元素?比如說,如果我試圖找到鄰居的元素位於最左側,並且我在它的左側搜索了一些東西 - 這是不存在的。我基本上只是尋找一種方法來'檢查'它是否有鄰居,然後我甚至不用做任何事情,所以我沒有得到一個IndexOutOfBoundsException。 – Vigilant
那麼,如果第二個索引是'0',就知道它在最左邊,那麼你也知道你不應該在左邊尋找鄰居。如果你正在處理元素'array [i] [j]',並且'j'等於'0',那麼不要搜索那個元素左邊的東西。 –