At some point, we need to forcibly terminate this or end loop when certain conditions arise, instead of waiting for the loop condition to be false, continue (ending this loop), break (jumping out of the loop body) is provided in Java to control the looping structure. In addition, return can end the entire method and, of course, end a cycle.
Break: Used to completely end a loop and jump out of the loop body.
Continue: Abort this cycle and start the next cycle
Public Static voidMain (string[] args) {intCount=0;//Print count initial value for(inti =1; I <= +; i++) { if(i%7==0)//is a multiple of 7 for the next loop. Continue; System. out. Print (i+"\ t"); Count++; if(count%4==0) System. out. println (); if(i== -) Break;//Jump out of the loop } }
The above code runs the result:
We can see from the above example that I = 7 or a multiple of 7, start the next loop, or print, count is the number of times the record is printed, count is a multiple of 4 or 4, the line is wrapped. I was equal to 100 when I jumped out of the loop body.
The break statement can not only end the loop in which it is located, but also directly end its outer loop. At this point, just follow the break statement followed by a label that identifies an outer loop.
The tag in Java is an identifier followed by a colon (:). Unlike other languages, tags in Java are only useful until they are placed in a circular statement.
Instance:
Public Static voidMain (string[] args) {auter: for(inti =0; I <Ten; i++) { for(intj =0; J <5; J + +) { if(J = =2) {System. out. Print ("Section"+ i +"Times"+j); BreakAuter; }} System. out. println (); } }
Results:
"Use the return End method
The return keyword is not designed to jump out of a loop, and the return function is to end a method. This method ends when a method executes to a return statement (return can also be used in combination with a variable, constant, expression).
Instance:
Public Static voidMain (string[] args) { for(inti =0; I <Ten; i++) { for(intj =0; J <5; J + +) { if(J = =2) {System. out. Print ("Section"+ i +"Times"+j); return; }} System. out. println (); } }
Results:
java--Control Loop structure