亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為鄰居過濾數組

為鄰居過濾數組

肥皂起泡泡 2022-07-27 11:33:02
有沒有一種簡單的方法可以快速過濾一組元素以僅輸出鄰居?假設我有一個元素數組?,F在我想找到特定元素的鄰居。我編寫的代碼有效,但看起來很丑,我想找到一個更易于閱讀的解決方案。我的代碼:int[] myArray = {6, 8, 9, 12, 30};// index of element where I want to find the neighbors ofint 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]);}
查看完整描述

2 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

這是一個很好的簡短解決方案:


if(index > 0) System.out.println(myArray[index-1])

if(index < array.length-1) System.out.println(myArray[index+1])


查看完整回答
反對 回復 2022-07-27
?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

實際上,使用 Java 8,您可以通過非常簡單的 lambda 解決方案來使用它:


final int[] numbs = { 1, 3, 5, 7 };

int index = 2;

IntStream.rangeClosed(index - 1, index + 1)

        .filter(idx -> idx != index && idx >= 0 && idx < numbs.length)

        .forEach(idx -> System.out.println(numbs[idx]));

但是,請創建一個接收數組和索引的方法,以便重用代碼。


查看完整回答
反對 回復 2022-07-27
  • 2 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號