classForLoopExample3 { publicstaticvoidmain(String args[]){ intarr[]={2,11,45,9}; //i starts with 0 as array index starts with 0 too for(inti=0; i<arr.length; i++){ System.out.println(arr[i]); } } } 输出: 2 11 45 9 增强型for循环 当您想要遍历数组/集合里面的每个元素时,...
下面是一个完整的示例,演示了如何声明一个长度为5的String数组,并使用for循环为数组赋值: publicclassStringArrayExample{publicstaticvoidmain(String[]args){String[]strArray=newString[5];for(inti=0;i<strArray.length;i++){strArray[i]="String"+i;}// 打印数组中的元素for(Stringstr:strArray){System....
(Java for loop Evolution) We will work on an example for displaying names of actors from aCollection. For the sake of simplicity let’s take aListand set this up: 我们将通过一个示例来显示Collection中演员的姓名。 为了简单起见,让我们列出一个列表并进行设置: List<String> actors = Arrays.asLi...
import java.util.ArrayList; import java.util.List; public class JavaForEachLoopExample { public static void main(String[] args) { int[] intArray = { 10, 20, 30, 40, 50 }; for (int i : intArray) System.out.println("Java for each loop with array - " + i); List<String> fruits...
for-each循环用于在java中遍历数组或集合。它比简单的for循环更容易使用,因为不需要递增值和使用下标符号。 语法: for(Typevar:array){//code to be executed} Java 示例: publicclassForEachExample{publicstaticvoidmain(String[] args){intarr[] = {12,23,44,56,78};for(inti : arr) { ...
2. Java For-loop Example In the following program, we are iterating over an array of int values. The array contains 5 elements so the loop will iterate 5 times, once for each value in the array. int[] array = new int[] {0, 1, 2, 3, 4}; for(int i = 0; i < array.length...
Java For LoopWhen you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:SyntaxGet your own Java Server for (statement 1; statement 2; statement 3) { // code block to be executed }...
publicclassForEachLoopExample{publicstaticvoidmain(String[] args){ System.out.println("For Each Loop Example: ");int[] intArray = {1,2,3,4,5};//Here iteration starts from index 0 to last indexfor(inti : intArray) System.out.println(i); } } ...
Java provides three types of loops, i.e., ✓ for loop ✓ while loop ✓ do-while loop. In this tutorial, you will learn all about for loop in Java. Start now!
publicclassLoopExample{publicstaticvoidmain(String[]args){intcount=0;for(inti=0;i<10;i++){count++;// 其他循环操作}System.out.println("循环遍历次数:"+count);count=0;int[]array={1,2,3,4,5};for(intnum:array){count++;// 其他循环操作}System.out.println("循环遍历次数:"+count);}} ...