【问题标题】:Avoid index exceptions in some exercise在某些练习中避免索引异常
【发布时间】:2021-09-03 08:35:52
【问题描述】:

对二维数组有疑问。我有一个维度为 n x n 的数组,类似于以下内容。

1 5 4 7
2 3 8 0
6 1 0 1
2 9 4 1

我需要获取数字右侧的所有元素。一个在右边,一个在对角线上,一个在对角线向下。例如,对于第二列中的 3,我必须得到 4、8 和 0。对于第一列中的 1,我必须得到 5 和 3(这个在对角线上没有邻居向上)。对于 7,它没有邻居。

用这个方法:

for(int i=0; i<n; i++){
    for(int j=0; j<n; j++){
        System.out.print("diagonal-up:" + myArray[i-1][j+1]); //indexOutboundException for the position [0][0] and for all in the last column and first row.
        System.out.print("rigth:" + myArray[i][j+1]); //indexOutboundException for all in the last column
        System.out.print("diagonal-down:" + myArray[i+1][j+1]); //indexOutboundException for all in the last row.
    }
}

如何更正此代码中的索引以避免索引异常

或者如果你知道一个更好的方法来解决这个练习,我真的很感激。

对不起,如果这个问题很愚蠢,但我正在学习使用矩阵。

【问题讨论】:

  • 当右边没有 3 个元素时,你想输出什么?
  • @iota,“无”或“没有元素”。

标签: java multidimensional-array indexoutofboundsexception


【解决方案1】:

您可以使用if 语句检查索引是否在范围内。

private static String getValue(int[][] arr, int i, int j){
    return i >= 0 && i < arr.length && j >= 0 && j < arr[i].length ? String.valueOf(arr[i][j]) : "no value";
}
for(int i=0; i<n; i++){
    for(int j=0; j<n; j++){
        System.out.print("diagonal-up:" + getValue(myArray, i-1, j+1) + " ");
        System.out.print("right:" + getValue(myArray, i, j+1) + " "); 
        System.out.println("diagonal-down:" + getValue(myArray, i+1, j+1)); 
    }
}

【讨论】:

    【解决方案2】:
        for(int j=0; j<n; j++){ 
            if (i-1 >= 0 && j+1 <n)
            System.out.print("diagonal-up:" + myArray[i-1][j+1]); 
            if (j+1 <n)
            System.out.print("rigth:" + myArray[i][j+1]); 
            if (i+1< n && j+1 <n)
            System.out.print("diagonal-down:" + myArray[i+1][j+1]); 
        }
    } ```
    
    You can add if conditions to check if the index that is going to be accessed even exists. another small improvement here, would be grouping the if clause for `(j+1 < n )` since it holds for all the three cases :) 
    

    【讨论】:

      猜你喜欢
      • 2012-01-31
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多