Click to enter _ more _java thousand ask
1. How to iterate through an array
When we work with arrays, we often use a for loop or a foreach loop to iterate because all the elements in the array are of the same type and the size of the array is known.
Learn what an array looks here: What is an array in Java
See the For loop here: How to Loop through Java
Use for loop traversal
Public classTestarray { Public Static void Main(string[] args) {Double[] MyList = {1.9,2.9,3.4,3.5};//Print all the array elements for(inti =0; i < mylist.length; i++) {System. out. println (Mylist[i] +" "); }//Summing all elements DoubleTotal =0; for(inti =0; i < mylist.length; i++) {total + = Mylist[i]; } System. out. println (" Total is"+ total);//Finding the largest element Doublemax = mylist[0]; for(inti =1; i < mylist.length; i++) {if(Mylist[i] > max) max = mylist[i]; } System. out. println ("Max is"+ max); }}
This will produce the following results:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Traversing with a foreach loop
JDK 1.5 introduces a new for loop called a Foreach loop or an enhanced for loop that iterates through an array sequentially without using an indexed variable.
publicclass TestArray { publicstaticvoidmain(String[] args) { double[] myList = {1.92.93.43.5}; // Print all the array elements for (double element: myList) { System.out.println(element); } }}
This will produce the following results:
1.9
2.9
3.4
3.5
Java FAQ _06 data structure (012) _ How to iterate over an array