[英]For loop what does this mean?
我目前正在學習Java,並且正在學習如何解析HTML。
我了解for循環的工作方式
例如:
for(int i = 0; i < 20; i++){
}
表示i為0,如果i小於20,則加1。
但是,這是什么意思????
for(Element newsHeadline: newsHeadlines){
System.out.println(newsHeadline.attr("href"));
}
我試圖用谷歌搜索但找不到答案
謝謝
這是一個foreach
循環。
newsHeadlines
是一個Element
類型的對象數組。
for(Element newsHeadline: newsHeadlines)
應該讀為
For each newsHeadline in newsHeadlines do
它到達newsHeadlines
的最后一個對象並完成該塊中的代碼后,它將結束。
希望現在您知道這是一個foreach循環,它將幫助您優化Google搜索。
這是一個for-each循環。 它使用迭代器遍歷集合
https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
For循環是原始for循環的一種簡短形式,但是沒有給定元素的索引。
舉個例子:
for(Element newsHeadline: newsHeadlines){
System.out.println(newsHeadline.attr("href"));
}
與:
Iterator<Element> it = newsHeadlines.iterator();
while(it.hasNext()){
Element newsHeadline = it.next();
System.out.println(newsHeadline.attr("href"));
}
如您所見,它更短並且更具可讀性。 簡而言之,它的意思是:對於集合中的每個元素都要做某事。 您可以遍歷任何可迭代的集合或數組。
這是for-each
循環。 它是編寫for循環而無需使用索引的簡寫。
String[] names = {"Alex", "Adam"};
for(int i = 0; i < names.length; i ++) {
System.out.println(names[i]);
}
for(String name: names) {
System.out.println(name);
}
這是一個迭代循環:每次迭代把收集的下一個元素newsHeadlines
內newsHeadline
。 簽出此線程: Java“ for each”循環如何工作?
我認為它將為您提供幫助。
例:
public class Test {
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
This would produce the following result:
10,20,30,40,50,
James,Larry,Tom,Lacy,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.