The foreach syntax eliminates the need to create an int variable to count the sequences made up of access items, and foreach automatically iterates through each
The foreach syntax is as follows
for (variable type x: sequence of this variable) {
Statement
}
The foreach statement is a special, simplified version of the for statement, but the foreach statement does not completely replace the For statement, however, any foreach statement can be rewritten as a for statement version. foreach is not a keyword, and it is customary to refer to this special for statement format as a "foreach" statement. From the literal meaning of the word foreach is "for each" meaning. That's actually what it means. foreach statement format: for (element type T element variable x: Traverse object obj) {References x's Java statement;} Here are two examples of simple examples of how foreach simplifies programming. The code is as follows:
Traversing a float array with a foreach
public class foreachfloat{
public static void Main (string [] args) {
Random rand = new Random (47);
float f[] = new FLOAT[10];
for (int i=0;i < 10;i++) {
F[i]=rand.nextfloat ();
}
for (float x:f)
System.out.println (x);
}
}
Output
0.32454357
.
.
. Total 10 lines
As shown in the previous example
for (float x:f) {
This statement defines a float variable named x, and then traverses each value to the X
}
Any array or return value that is an array of methods can be applied to foreach.
public class foreachstring{
Publicn static void Main (string [] args) {
for (char c: "Hello word". ToCharArray ()) {
System.out.print (c+ "");
}
}
}
Output
H e l l o w o r d
However, foreach cannot iterate directly over a set of logical numbers that do not exist, but for it can
For example for (int i=0;i < 100;i++)
If you want to traverse a number directly, you need to create an array of int, but you can do a static method that automatically builds an array based on the number you pass in.
For example for (int i:range (10))
Although this method can make foreach more general, this method will reduce the efficiency of the computer
/**
* foreach output two dimensional array test
*/
public void Testarray2 () {
int arr2[][] = {4, 3}, {1, 2}};
System.out.println ("----3----foreach output two-dimensional array test");
for (int x[]: arr2) {
for (int e:x) {
System.out.println (e); Output the value of an array element individually
}
}
}
/**
* foreach output three-dimensional array
*/
& nbsp; public void Testarray3 () {
int arr[][][] = {
{1, 2}, {3, 4}},
{5, 6}, {7, 8}}}
};
System.out.println ("----4----foreach output three-dimensional array test");
for (int[][] a2:arr) {
for (int[] a1:a2) {
for (int x:a1) {
System.out.println (x);
}
}
}
}