【发布时间】: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