Java array usage and foreach loop

Java array usage and foreach loop

Without saying a word, let's start with a simple procedure:

final int NUM= 10;
int[] arrays = new int[NUM];
System.out.println(arrays.length);//10
for(int i = 0;i<5;i++){
    arrays[i] = i;//赋值
}
//foreach
for(int element:arrays){
    System.out.print(element+" ");
}
// 0 1 2 3 4 0 0 0 0 0

foreach loop

Format:

for(元素类型 元素:数组名){...}

be careful:

int []arrays = {1,2,3,4,5};
// int i;
System.out.println("使数组中每个元素加1");
for(int i:arrays){
    i+=1;
    System.out.print(i+" ");
}
System.out.println();
System.out.println("修改后:");
for(int j:arrays){
    System.out.print(j+" ");
}	
/**
使数组中每个元素加1
2 3 4 5 6
修改后:
1 2 3 4 5*/
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>