2016-03-01 36 views
0

我試圖找到可以放置在NxN二維數組中的任何位置的特定元素(數字0)的鄰居。如果0位於中心位置,則這不成問題,但如果它位於頂部/底部的行上,則不會有高於/低於其的值,並且與最左側/右側相同角落案件。應該指出,我只需要檢查直接水平/垂直於它的值,而不是對角線。是否有可以調用的特定方法來確定特定索引是否存在?試圖找出如何檢查一個潛在的數組元素是否超出範圍

回答

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

正確,但如果[0] [whatever]導致一個不存在的元素?比如說,如果我試圖找到鄰居的元素位於最左側,並且我在它的左側搜索了一些東西 - 這是不存在的。我基本上只是尋找一種方法來'檢查'它是否有鄰居,然後我甚至不用做任何事情,所以我沒有得到一個IndexOutOfBoundsException。 – Vigilant

+0

那麼,如果第二個索引是'0',就知道它在最左邊,那麼你也知道你不應該在左邊尋找鄰居。如果你正在處理元素'array [i] [j]',並且'j'等於'0',那麼不要搜索那個元素左邊的東西。 –

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){ 

} 
} 
相關問題