The difference between break continue return
| Key words |
Position |
Role |
| Break |
Switch and loop |
End Loop |
| Continue |
Cycle |
End this cycle and proceed to the next cycle |
| Return |
Used anywhere in the method |
End method |
Use break in A for loop
1 intscore;2 intSum=0;3 inti;4 for(i=1;i<=5;i++){5System.out.println ("Please enter your score");6Scanner scanner=NewScanner (system.in);7Score=scanner.nextint ();8 if(score<0){9SYSTEM.OUT.PRINTLN ("Input error, re-enter");Ten Break;//End for Loop One } A -sum+=score; - the - } - if(i==6){ -System.out.println ("Average score" + (SUM/5)); +}
Use break in switch
1 Switch(number) {2 Case1:3System.out.println ("Square");4 Break;//Jump out of switch5 Case2:6System.out.println ("Triangle");7 Break;8 Case3:9System.out.println ("Round");Ten Break; One default: ASYSTEM.OUT.PRINTLN ("Input Error"); - Break; -}
Use continue in for
1 /**an even number of output 1~10*/2 Public classTest {3 Public Static voidMain (string[] args) {4 for(inti=1;i<=10;i++){5 if(i%2!=0){6 Continue;//If I is not an even number, do not execute the subsequent output statement and continue with the For loop7 }8 System.out.println (i);9 }Ten } One}
Return
1 Public classTest {2 Public Static voidMain (string[] args) {3A://Define a here4 for(inti=1;i<=5;i++){5 for(intj=1;j<=5;j++){6 /**7 * if (i==3) {8 *//break; End Inner Loop9 *//Break A; End of outer loop printout final EndTen *//return; Ends the entire program, does not print out the final "end" statement One * } A * - * */ - the - if(j==3){ - //continue;//end this inner loop - ContinueA//end this outer loop + - } +System.out.print (i+ "Row" +j+ "column"); A } at System.out.println (); - } -System.out.println ("End"); - } -}
Java Basic Four