//add adj nodes
try{
for(int r2 = 0; r2 < rows; r2++){
for(int c2 = 0; c2 < cols; c2++){
Node currentNode = nodeGrid[r2][c2];
Node rightNode = nodeGrid[r2][c2+1];
Node bottomNode = nodeGrid[r2+1][c2];
if(!rightNode.isWall()){
currentNode.addNeighbor(rightNode);
}
if(!bottomNode.isWall()){
currentNode.addNeighbor(bottomNode);
}
}
}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("no next node");
}
您好,鉴于我有这个2D数组,并且我想访问下一个元素,我最终会达到一个超出范围的索引,是否还有其他解决方法来访问下一个元素?
答案 0 :(得分:1)
您必须更仔细地检查您的指数:
for(int r2 = 0; r2 < rows; r2++){
for(int c2 = 0; c2 < cols; c2++){
Node currentNode = nodeGrid[r2][c2];
Node rightNode = null;
if (c2 < cols - 1) // the condition for the existence of a right node
rightNode = nodeGrid[r2][c2+1];
Node bottomNode = null;
if (r2 < rows - 1) // the condition for the existence of a bottom node
bottomNode = nodeGrid[r2+1][c2];
if(rightNode != null && !rightNode.isWall()){
currentNode.addNeighbor(rightNode);
}
if(bottomNode != null && !bottomNode.isWall()){
currentNode.addNeighbor(bottomNode);
}
}
}