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

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

是否有可能檢查 foreach 循環中的上一個和下一個元素?

是否有可能檢查 foreach 循環中的上一個和下一個元素?

狐的傳說 2023-11-01 22:00:01
在java中使用foreach如何檢查上一個和下一個元素。是否有可能檢查每個循環中的上一個和下一個元素
查看完整描述

4 回答

?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

for Each 循環的一些限制。

另外,這可以是一種方式:

? ? public class Main

{

? ? public static void main(String[] args) {

? ? String[] arr={"a","b"};

? ? String next="";

? ? String current="";

? ? String prev="";


? ? for(int i=0;i<arr.length;i++){


? ? ? ? //previousElement

? ? ? ? if(i>0){?

? ? ? ? ? ? prev=arr[i-1] ;

? ? ? ? ? ? System.out.println("previous: "+prev);

? ? ? ?}else{

? ? ? ? ? ?prev="none";

? ? ? ? ? System.out.println("previous: "+prev);

? ? ? ? ? ? ? ?}


? ? ? ? ?//currentElement? ? ??

? ? ? ? current=arr[i];

? ? ? ?System.out.println(" current: "+current);


? ? ? ?//nextElement

? ? ? if(i<arr.length-1){

? ? ? ? ? next=arr[i+1];

? ? ? ? ? System.out.println(" next: "+next);

? ? ? ? ? ? ? }else{

? ? ? ? ? ? ? ? ? next="none";

? ? ? ? ? ? ? ? ? System.out.println(" next: "+next);

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? }

? }

}

還附加輸出:

https://img1.sycdn.imooc.com/65425a100001cb2806480567.jpg



查看完整回答
反對 回復 2023-11-01
?
慕田峪9158850

TA貢獻1794條經驗 獲得超7個贊

不。

“foreach”結構使用了Iteratorunderlying,它只有一個next()andhasNext()函數。沒有辦法得到previous()。

Lists有一個ListIterator允許查看前一個元素,但“foreach”不知道如何使用它。因此,唯一的解決方案是記住單獨變量中的前一個元素,或者僅使用像這樣的簡單計數循環:for(int i=0;i< foo.length();i++)。


查看完整回答
反對 回復 2023-11-01
?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

使用“foreach”只有next()和hasNext()方法,因此它不提供反向遍歷或提取元素的方法。


考慮到您有一個字符串 ArrayList,您可以使用java.util.ListIterator它提供的方法,例如hasPrevious()和previous()


下面是如何使用它的示例。** 閱讀代碼一側的注釋,因為它包含使用這些方法的重要細節。**


        ArrayList<String> mylist = new ArrayList<>();


        ListIterator<String> myListIterator = mylist.listIterator();


        myListIterator.hasNext(); // Returns: true if list has next element

        myListIterator.next(); // Returns: next element , Throws:NoSuchElementException - if the iteration has no next element

        myListIterator.hasPrevious(); // Returns: true if list has previous element

        myListIterator.previous(); //Returns: the previous element in the list , Throws: NoSuchElementException - if the iteration has no previous element

希望這可以幫助。


PS:您應該發布到目前為止所做的代碼,在 stackoverflow 上發布問題,其中不包含任何內容來表明您的努力確實很糟糕。


查看完整回答
反對 回復 2023-11-01
?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

這樣做的目的是什么?


foreach您可能應該使用for循環和索引來代替 a


for(int i=0;i<lenght;i++) {

    list[i-1].dostuff //previous

    list[i].dostuff //current

    list[i+1].dostuff //next item

}

并且不要忘記檢查下一項和上一項是否存在。


查看完整回答
反對 回復 2023-11-01
  • 4 回答
  • 0 關注
  • 249 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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