Summary: Java newcomers to some of their own understanding of the first, the big God passing do not spray, there is nothing to say the wrong place to give guidance, if you think you can, hope can point a praise, hey, here first thanks. What I'm talking about here is the usage and the difference of the Java three loop body used in beginners: when and when will make the program code more convenient and concise;
A. For loop body, this after I write the program code is a long use of one of the loop body, the for loop mostly used in the loop program we already know the number of cycles.
Expression: for (initialization; Boolean expression; update) {
Program code .....
}
For example: Calculate the result of 1+2+3...............+100;
Public class Forxunhuan { publicstaticvoid main (string[] args) { int f=1; for (int c=2; c<=; c + +) {//1+2+3......+100 f=f+c; } System. out . println (f); }}
Two. While loop body, is also one of the more commonly used loops in Java, while loop is mainly used in the case of unknown cycle times;
Expression: (Boolean expression) {
Loop code .....
}
Example: Given a need to move the number of socks, when the cycle to our set number, is not in circulation, that is, stop moving socks;
ImportJava.util.*; Public classWhile { Public Static voidMain (string[] args) {Scanner in=NewScanner (system.in); System.out.println ("Please enter the number of socks to be moved:"); intM =In.nextint (); intA = 0; while(A <M) {a++; } System.out.println ("Move to" + A + "double socks"); }}
Three. Do While loop body, when writing code, not much, do while still suitable for the construction of the loop number is unknown, but at least 1 times to execute the loop program.
Expression: do{
Loop the code statement ....
}while (Boolean expression)
Example: The output of 100 from 10 start each time the number of 10 increase;
Public class Sanjiaoxing1 { publicstaticvoid main (string[] args) { int y=10; Do { System.out.println (y); Y+=10; } while (y<100);} }
The use and difference of three kinds of cycles in Java Foundation