有没有一种简单的方法可以快速过滤一组元素以仅输出邻居?
假设我有一个元素数组。现在我想找到特定元素的邻居。
我编写的代码有效,但看起来很丑,我想找到一个更易于阅读的解决方案。
我的代码:
int[] myArray = {6, 8, 9, 12, 30};
// index of element where I want to find the neighbors of
int index = 1;
if(index == 0){
//first element so only add the right neighbor
System.out.println(myArray[1]);
} else if(index == myArray.length -1){
//last element so only add left neighbor
System.out.println(myArray[index-1]);
} else{
//middle element so add both neighbors
System.out.println(myArray[index-1]);
System.out.println(myArray[index+1]);
}
海绵宝宝撒
一只甜甜圈
相关分类