加強型for循環

           foreach循環,這種循環遍歷數組和集合更加簡潔。使用foreach循環遍歷數組和集合時,無須得到數組和集合的長度,無需根據訪問數組元素和集合元素,foreach自動遍歷數組和集合的每一個元素。 數組

語法格式以下: io

  for(type variableName : array | collection){ class

            //vairableName  自動迭代訪問每一個元素…… 變量

} foreach

例子: 循環

public class dfdf {
       public static void main(String args []){
  
             String books [] = {"123","456","789"};
             for(String number : books){
                 System.out.println(number);
                 number = "aaa";
            }
           System.out.println(books[0]);
     } 遍歷

 } 語法

  輸出結果: static

         123
         456
         789
         123 集合

 

 

注意:一般狀況下不要對循環變量進行賦值,雖然語法上是容許的,但極容易引發錯誤。(循環過程不會改變數組或集合中元素值)

相關文章
相關標籤/搜索